Go中的struct之方法method初体验

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

// code_017_struct_method_usage project main.go
package main

import (
    "fmt"
)

type MyInt int

func (a MyInt) Add(b MyInt) MyInt {
    return a + b
}

func Add(a, b MyInt) MyInt {
    return a + b
}

type Person struct {
    name string
    sex  byte
    age  int
}

func (p Person) PrintInfo() {
    fmt.Println(p.name, p.age)
}

func (p *Person) SetInfoPointer() {
    (*p).name = "god_girl"
    p.sex = 1
    p.age = 22
}

func (p Person) SetInfoValue() {
    p.name = "god_like"
    p.sex = 1
    p.age = 23
}

func main() {
    /*
        带有接收者的函数,我们称之为方法(method).本质上,一个方法则是一个和特殊类型关联的函数。
        func (receiver ReceiverType) funcName(parameters){results}
        1)参数 receiver 可任意命名。如方法中未曾使用,可省略参数名。
        参数 receiver 类型可以是 T 或 *T。基类型 T 不能是接口或指针。
        不支持重载方法,也就是说,不能定义名字相同但是不同参数的方法。
        2)在 Go 语言中,可以给任意自定义类型(包括内置类型,但不包括指针类型)添加相应的方法。

    */
    //1) 基本使用
    var a MyInt = 1
    var b MyInt = 1

    fmt.Println("a.Add(b)=", a.Add(b))
    fmt.Println("Add(a,b)=", Add(a, b))
    //2)结构体作为接收者
    p := Person{"ck_god", 0, 18}
    p.PrintInfo()

    //3)结构体的值语义和引用语义

    p1 := Person{"wanglaoji", 0, 27}
    fmt.Println("函数调用前= ", p1)
    (&p1).SetInfoPointer()
    fmt.Println("函数调用后=", p1)

    fmt.Println("==========================")
    p2 := Person{"ck_god", 0, 18}
    fmt.Println("函数调用前 = ", p2)
    p2.SetInfoValue()
    fmt.Println("函数调用后 = ", p2) //函数调用后 =  {mike 109 18}

}

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

查看所有标签

猜你喜欢:

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

The Lean Startup

The Lean Startup

Eric Ries / Crown Business / 2011-9-13 / USD 26.00

更多中文介绍:http://huing.com Most startups fail. But many of those failures are preventable. The Lean Startup is a new approach being adopted across the globe, chan ging the way companies are built and ......一起来看看 《The Lean Startup》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

SHA 加密
SHA 加密

SHA 加密工具