Go语言的方法值和方法表达式

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

内容简介:结果如下:
// code_20_struct_method_expression project main.go
package main

import (
    "fmt"
)

//方法表达式:也即“方法对象赋值给变量”
//两种使用方式:
//1)隐式调用, struct实例获取方法对象---->方法值

//2)显示调用, struct类型获取方法对象, 须要传递struct实例对象作为参数。---->方法表达式

type Person struct {
    name string
    sex  byte
    age  int
}

func (p *Person) PrintInfoPointer() {
    fmt.Printf("%p, %v\n", p, p)
}

func (p Person) PrintInfoValue() {
    fmt.Printf("%p, %v\n", &p, p)
}

func main() {
    //直接调用
    p := Person{"ck_god", 'm', 18}
    p.PrintInfoPointer()
    fmt.Println("---------------\n")

    //方法表达式
    pFunc1 := (*Person).PrintInfoPointer
    pFunc1(&p)

    pFunc2 := Person.PrintInfoValue
    pFunc2(p)
    fmt.Println("---------------\n")

    //方法值
    pFunc3 := p.PrintInfoPointer
    pFunc3()

    pFunc4 := p.PrintInfoValue
    pFunc4()
    fmt.Println("---------------\n")

    //备注:pFunc2和pFunc4的内存地址是不一样的;pFunc1和pFunc3的内存地址是一致的
}

结果如下:

0xc000050400, &{ck_god 109 18}
---------------

0xc000050400, &{ck_god 109 18}
0xc000050480, {ck_god 109 18}
---------------

0xc000050400, &{ck_god 109 18}
0xc0000504e0, {ck_god 109 18}
---------------

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

查看所有标签

猜你喜欢:

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

Distributed Systems

Distributed Systems

Sukumar Ghosh / Chapman and Hall/CRC / 2014-7-14 / USD 119.95

Distributed Systems: An Algorithmic Approach, Second Edition provides a balanced and straightforward treatment of the underlying theory and practical applications of distributed computing. As in the p......一起来看看 《Distributed Systems》 这本书的介绍吧!

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

各进制数互转换器

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

RGB CMYK 互转工具

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

HSV CMYK互换工具