在尝试创建链表数据结构时,我声明了两个结构。
package main
import "fmt"
type listElement struct {
data int
next *listElement
}
type List struct {
first *listElement
last *listElement
len int
}
我想创建一个返回空列表的方法。到目前为止,我只能创建函数
func new() *List {
return &List{}
}
这与我在多个数据结构存储库中看到的结果相同。是否可以创建一个方法 List.new()
来返回一个新的空列表?
最佳答案
是的,您当然可以定义一个返回 List 值的方法,但是由于您需要一个 List 值来调用方法,这有点尴尬:
package main
type List struct{}
func (List) New1() *List {
return &List{}
}
func (*List) New2() *List {
return &List{}
}
func main() {
_ = List{}.New1()
_ = (&List{}).New2()
_ = (*List)(nil).New2()
}
老实说,我看不出这比 Go 中惯用的 NewList 函数有什么好处:
func NewList() *List {
return &List{}
}
如果您的包名为 list,请将函数命名为 New,因此它被称为 list.New()
。
参数和正文在所有情况下都是相同的。它们仅在调用方式上有所不同,并且包函数最容易使用。 (请参阅 JimB 评论中的链接,了解另一种略有不同的变体。)
看来你还没有读过Effective Go , 这表明了上述大部分内容。
The function to make new instances of ring.Ring—which is the definition of a constructor in Go—would normally be called NewRing, but since Ring is the only type exported by the package, and since the package is called ring, it's called just New, which clients of the package see as ring.New.
关于go - 在 Go 语言中返回其结构地址的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49464590/