如何设置和获取字段在Golang结构?

在创建一个这样的结构:
type Foo struct {
   name string        

}
func (f Foo) SetName(name string){
    f.name=name
}

func (f Foo) GetName string (){
   return f.name
}

如何创建一个新的Foo实例并设置和获取名称
我试过以下:

p:=new(Foo)
p.SetName("Abc")
name:=p.GetName()
fmt.Println(name)

没有打印,因为名称是空的。那么如何设置和获取结构体中的字段?

评论(和工作)示例:
package main

import "fmt"

type Foo struct {
    name string
}

// SetName receives a pointer to Foo so it can modify it.
func (f *Foo) SetName(name string) {
    f.name = name
}

// Name receives a copy of Foo since it doesn't need to modify it.
func (f Foo) Name() string {
    return f.name
}

func main() {
    // Notice the Foo{}. The new(Foo) was just a syntactic sugar for &Foo{}
    // and we don't need a pointer to the Foo,so I replaced it.
    // Not relevant to the problem,though.
    p := Foo{}
    p.SetName("Abc")
    name := p.Name()
    fmt.Println(name)
}

Test it并采取A Tour of Go以了解更多关于方法和指针,以及Go的基本知识。

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...