Go中的方法集

栏目: Go · 发布时间: 7年前

内容简介:类型*T方法集类型T的方法集

类型*T方法集

// code_018_struct_method_set project main.go
package main

import (
    "fmt"
)

//类型*T方法集
type Person struct {
    name string
    sex  byte
    age  int
}

//指针作为接收者,引用语义
func (p *Person) SetInfoPointer() {
    (*p).name = "yoyo"
    p.sex = 'f'
    p.age = 22
}

//值作为接收者,值语义
func (p Person) SetInfoValue() {
    p.name = "xxx"
    p.sex = 'm'
    p.age = 33
}

func main() {
    //p 为指针类型
    var p *Person = &Person{"mike", 'm', 18}
    p.SetInfoPointer() //func (p) SetInfoPointer()
    fmt.Println(p)

    p.SetInfoValue() //func (*p) SetInfoValue()
    fmt.Println(p)
    (*p).SetInfoValue() //func (*p) SetInfoValue()
    fmt.Println(p)
}

类型T的方法集

// code_018_struct_method_set2 project main.go
package main

import (
    "fmt"
)

//类型T方法集
type Person struct {
    name string
    sex  byte
    age  int
}

func (p *Person) SetInfoPointer() {
    (*p).name = "yoyo"
    p.sex = 'f'
    p.age = 22
}

func (p Person) SetInfoValue() {
    p.name = "xxx"
    p.sex = 'm'
    p.age = 33
}

func main() {
    //p为普通类型
    var p Person = Person{"ck_go", 'm', 18}
    (&p).SetInfoPointer()
    p.SetInfoPointer()

    p.SetInfoValue()
    (&p).SetInfoValue()
    fmt.Println(p)
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pragmatic Thinking and Learning

Pragmatic Thinking and Learning

Andy Hunt / The Pragmatic Bookshelf / 2008 / USD 34.95

In this title: together we'll journey together through bits of cognitive and neuroscience, learning and behavioral theory; you'll discover some surprising aspects of how our brains work; and, see how ......一起来看看 《Pragmatic Thinking and Learning》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

随机密码生成器
随机密码生成器

多种字符组合密码

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具