在Golang中,Java ArrayList<E>的等价物是什么?

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

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&lt;Channel&gt; channels = new ArrayList&lt;Channel&gt;();

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:&quot;some channel name&quot;})

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”维基页面。

英文:

Use slices.

For details on common slice idioms see the "Slice Tricks" wiki page.

huangapple
  • 本文由 发表于 2012年4月8日 13:55:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/10060728.html
匿名

发表评论

匿名网友

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

确定