Go中的Getter和Setter约定 [英] Getter and Setter conventions in Go

查看:198
本文介绍了Go中的Getter和Setter约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

案例A 不遵循Getter&传承人约定

Case A Not following the Getter & Setter convention

human / human.go

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

main/main.go

package main

func main() {
    john := Person{Name:"john"} // Uppercase Fields are visible
    fmt.Println(john)
}






案例B 遵循getter和setter约定


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

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.

推荐答案

实例化结构(或对象,在面向对象的语言中),则无论如何都不应指定私有字段的值。但是,提供可能以私有字段结尾或以完全不同的方式处理的数据是有意义的。在这种情况下,OOP保证使用构造函数,而Go约定是一种提供称为New [YourStructure]的功能的函数。

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…).

这篇关于Go中的Getter和Setter约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆