Golang自定义结构体中的引用列表

huangapple go评论80阅读模式
英文:

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

我可以看到两个问题:

  1. 导入fmt包但没有使用它。在Go中,未使用的导入会导致编译时错误;
  2. 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:

  1. importing the fmt package without using it. In Go unused imports result in compile-time errors;
  2. foo is not declared correctly: list is a package name not a type; you want to use a type from the container/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.

huangapple
  • 本文由 发表于 2013年7月7日 01:39:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/17505461.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定