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)
}

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

查看所有标签

猜你喜欢:

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

HTML & XHTML

HTML & XHTML

Chuck Musciano、Bill Kennedy / O'Reilly Media / 2006-10-27 / GBP 39.99

"...lucid, in-depth descriptions of the behavior of every HTML tag on every major browser and platform, plus enough dry humor to make the book a pleasure to read." --Edward Mendelson, PC Magazine "Whe......一起来看看 《HTML & XHTML》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具