gpt4 book ai didi

go - 是否可以将变量 "embedded variables"添加到结构中?

转载 作者:数据小太阳 更新时间:2023-10-29 03:43:56 25 4
gpt4 key购买 nike

type UserModel struct {
...
}

func (u *UserModel) C() string {
return "system_users"
}

上面将一个嵌入的结构分配给类型 UserModel,Go 是否允许用 vars 或 consts 做同样的事情?

有点像

var (u *UserModel) C = "system_users"

你明白了。

最佳答案

方法

方法是一个函数,其接收者绑定(bind)到一个类型。接收方可以采用一个值或一个指向方法绑定(bind)到的类型的指针。

Go by example 提供了这个很好的 example :

type rect struct {
width, height int
}

// This `area` method has a _receiver type_ of `*rect`.
func (r *rect) area() int {
return r.width * r.height
}

// Methods can be defined for either pointer or value
// receiver types. Here's an example of a value receiver.
func (r rect) perim() int {
return 2*r.width + 2*r.height
}

是的,您可以在除interface 之外的几乎所有现有类型上定义方法。它也必须是本地类型(在包中定义而不是内置的)

type Int int

func (i Int) Add(j Int) Int {
return i + j
}

嵌入

概括一下“Effective Go”:

嵌入类型的方法是免费的。这意味着如果类型 B 嵌入到类型 A 而不是类型 A 不仅有自己的方法它还有类型 B 的方法。

扩展前面的例子:

type parallelogram struct {
rect // Embedding. parallelogram has area and perim methods
depth int
}

func (p parallelogram) volume () int { // Extending rect
// Volume logic
}

关于go - 是否可以将变量 "embedded variables"添加到结构中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41971939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com