英文:
Golang reference list from within custom struct
问题
我有以下的代码块:
package main
import (
"fmt"
"container/list"
)
type Foo struct {
foo list //想要引用语言提供的list实现的引用
//supplied by the language
}
func main() {
//empty
}
编译时我收到以下消息:
use of package list not in selector
我的问题是,如何在struct
中引用list
?或者在Go中这不是包装结构的正确用法吗?(组合)
英文:
I have the following block of code:
package main
import (
"fmt"
"container/list"
)
type Foo struct {
foo list //want a reference to the list implementation
//supplied by the language
}
func main() {
//empty
}
When compiling I receive the following message:
> use of package list not in selector
My question is, how do I reference list
within a struct
? Or is this not the proper idiom in Go for wrapping structures. (Composition)
答案1
得分: 4
我可以看到两个问题:
- 导入
fmt
包但没有使用它。在Go中,未使用的导入会导致编译时错误; foo
没有正确声明:list
是一个包名而不是类型;你想要使用container/list
包中的类型。
修正后的代码:
package main
import (
"container/list"
)
type Foo struct {
// list.List代表一个双向链表。
// list.List的零值是一个空链表,可以直接使用。
foo list.List
}
func main() {}
你可以在Go Playground中执行上述代码。
你还应该考虑阅读container/list
包的官方文档。
根据你想要做什么,你可能还想知道Go允许在结构体或接口中嵌入类型。在Effective Go指南中阅读更多内容,并决定是否对你的特定情况有意义。
英文:
I can see two problems:
- importing the
fmt
package without using it. In Go unused imports result in compile-time errors; foo
is not declared correctly:list
is a package name not a type; you want to use a type from thecontainer/list
package.
Corrected code:
package main
import (
"container/list"
)
type Foo struct {
// list.List represents a doubly linked list.
// The zero value for list.List is an empty list ready to use.
foo list.List
}
func main() {}
You can execute the above code in the Go Playground.
You should also consider reading the official documentation of the container/list
package.
Depending on what you're trying to do, you might also want to know that Go allows you to embed types within a struct or interface. Read more in the Effective Go guide and decide wether or not this makes sense for your particular case.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论