Get语言和西特尔习惯用语

Get语言和西特尔习惯用语

本文介绍了Get语言和西特尔习惯用语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

案例A 不遵循Getter& Setter convention

human / human.go

  package human 

类型人类界面{
GetName()字符串
SetName(名称字符串)
}

类型Person结构{
名称字符串

$ b 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约定

 包人类

类型人类界面{
名称()字符串
SetName(名称字符串)
}

类型Person结构{
名称字符串
}

func(p Person)Name()string {
return p.name
}

func(p * Person)SetName(name string){
p.name = name
}
$ b $ main $ main $ go
$ b $ pre $ $ $ $ c $ package $ main

func main(){
john:= Person(name:John)//小写名称在包外不可见
}

以下约定的问题是我无法在提供其字段名的同时实例化结构。

解决方案

当实例化一个结构体(或对象,在面向对象的语言中),你不应该指定专用字段的值。然而,提供可能以私人领域结束的数据或者以完全不同的方式处理数据是有意义的。在这种情况下,OOP保证使用构造函数,Go惯例是提供称为New [YourStructure]的函数。

  func NewPerson(name string)Person {
return Person {name: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.

解决方案

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

这篇关于Get语言和西特尔习惯用语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:02