英文:
What is the equivalent of a Java ArrayList<E> in Golang?
问题
type Channel struct {
name string
}
var channels []Channel
英文:
In my particular use case, I would like to know how the following Java code would be implemented in Go -
class Channel {
public String name;
public Channel(){}
}
ArrayList<Channel> channels = new ArrayList<Channel>();
I've gotten started, and I think this would be the appropriate struct for Channel in Go -
struct Channel {
name string
}
I just need to know how ArrayList would work in Go
答案1
得分: 46
使用切片:
var channels []Channel // 一个空列表
channels = append(channels, Channel{name:"some channel name"})
另外,你的Channel声明有点问题,你需要使用'type'关键字:
type Channel struct {
name string
}
这是一个完整的示例:http://play.golang.org/p/HnQ30wOftb
更多信息,请参阅slices article。
还有go tour (tour.golang.org) 和语言规范 (golang.org/ref/spec, 参见 #Slice_types, #Slices, 和 #Appending_and_copying_slices)。
英文:
Use a slice:
var channels []Channel // an empty list
channels = append(channels, Channel{name:"some channel name"})
Also, your Channel declaration is slightly off, you need the 'type' keyword:
type Channel struct {
name string
}
Here's a complete example: http://play.golang.org/p/HnQ30wOftb
For more info, see the slices article.
There's also the go tour (tour.golang.org) and the language spec (golang.org/ref/spec, see #Slice_types, #Slices, and #Appending_and_copying_slices).
答案2
得分: 1
使用切片。
有关常见切片技巧的详细信息,请参阅“Slice Tricks”维基页面。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论