英文:
Getter and Setter conventions in Go
问题
案例A 不遵循Getter和Setter约定
human/human.go
package human
type Human interface {
GetName() string
SetName(name string)
}
type Person struct {
Name string
}
func (p Person) GetName() string {
return p.Name
}
func (p *Person) SetName(name string) {
p.Name = name
}
main/main.go
package main
func main() {
john := Person{Name: "john"} // 大写的字段是可见的
fmt.Println(john)
}
案例B 遵循Getter和Setter约定
package human
type Human interface {
Name() string
SetName(name string)
}
type Person struct {
name string
}
func (p Person) Name() string {
return p.name
}
func (p *Person) SetName(name string) {
p.name = name
}
main/main.go
package main
func main() {
john := Person{name: "John"} // 小写的name在包外不可见
}
遵循约定的问题是,我无法在实例化结构体时提供其字段名。我想使用这个约定,但我被私有访问所限制。
英文:
Case A Not following the Getter & Setter convention
human/human.go
package human
type Human interface {
GetName() string
SetName(name string)
}
type Person struct {
Name string
}
func (p Person) GetName() string {
return p.Name
}
func (p *Person) SetName(name string) {
p.Name = name
}
main/main.go
package main
func main() {
john := Person{Name:"john"} // Uppercase Fields are visible
fmt.Println(john)
}
Case B Following getter and setter convention
package human
type Human interface {
Name() string
SetName(name string)
}
type Person struct {
name string
}
func (p Person) Name() string {
return p.name
}
func (p *Person) SetName(name string) {
p.name = name
}
main/main.go
package main
func main() {
john := Person(name: "John") // lowercase name is not visible outside the package
}
The problem with following convention is that I can't instantiate the struct while providing its field names. I'd like to use the convention but I am stuck with the private access.
答案1
得分: 20
在实例化一个结构体(或者在面向对象的语言中,实例化一个对象)时,你不应该直接指定私有字段的值。然而,提供可能最终存储在私有字段中或以完全不同方式处理的数据是有意义的。在这种情况下,面向对象编程(OOP)需要使用构造函数,而Go语言的约定是提供一个名为New[YourStructure]的函数。
在这个简单的例子中,name只是简单地复制到私有字段中,但在更复杂的例子中,可能会进行其他操作(例如,检查name是否有效,或者查找name并根据结果采取相应的操作...)。
英文:
When instantiating a structure (or object, in object oriented languages), you should not specify the value of private fields anyway. It can make sense, however, to provide data that may end up in private fields, or be treated in a completely different manner. In this case, OOP warrants the use of a constructor, and the Go convention is a to provide a fuction called New[YourStructure].
func NewPerson(name string) Person {
return Person{name: name}
}
In this trivial example, the name is simply copied to the private field, but in a more complex example, other operations could take place (e.g. checking that the name is valid, or looking up the name and taking action depending on the result…).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论