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

时间:2012-08-04 16:32:19

标签: struct get set go

创建这样的结构后:

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)

没有打印任何内容,因为名称为空。那么如何在结构中设置和获取字段?

3 个答案:

答案 0 :(得分:107)

评论(和工作)示例:

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的基础知识。

答案 1 :(得分:24)

Setter和getter不是 非惯用的Go。 特别是字段x的getter不是GetX 但只是X. 见http://golang.org/doc/effective_go.html#Getters

如果设定者没有提供特殊逻辑,例如 验证逻辑,导出没有任何问题 该领域既不提供制定者也不提供吸气剂 方法。 (对于有这种情况的人来说,这感觉不对 Java背景。但事实并非如此。)

答案 2 :(得分:4)

例如,

package main

import "fmt"

type Foo struct {
    name string
}

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

func (f *Foo) Name() string {
    return f.name
}

func main() {
    p := new(Foo)
    p.SetName("Abc")
    name := p.Name()
    fmt.Println(name)
}

输出:

Abc
相关问题