nop*_*ope 54 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
}
Run Code Online (Sandbox Code Playgroud)
如何创建Foo的新实例并设置并获取名称?我尝试了以下方法:
p:=new(Foo)
p.SetName("Abc")
name:=p.GetName()
fmt.Println(name)
Run Code Online (Sandbox Code Playgroud)
没有打印,因为名称是空的.那么如何设置并获取结构中的字段?
Mos*_*vah 112
评论(和工作)示例:
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)
}
Run Code Online (Sandbox Code Playgroud)
测试它并参加A Tour of Go以了解有关方法和指针的更多信息,以及Go的基础知识.
Vol*_*ker 24
getter和setter方法是不是那个地道为Go.特别是字段x的getter不是名为GetX而只是X.请参阅http://golang.org/doc/effective_go.html#Getters
如果setter没有提供特殊的逻辑,例如验证逻辑,那么导出字段并没有提供setter或getter方法都没有错.(对于拥有Java背景的人来说,这感觉不对.但事实并非如此.)
例如,
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)
}
Run Code Online (Sandbox Code Playgroud)
输出:
Abc
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79187 次 |
| 最近记录: |