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
Python lists are similar to arrays in languages like C and Java in that these all represent ways to group variables together. But, a list in Python is more closely related to the ArrayList object in Java. This is because ArrayLists in Java and lists in Python can grow in size as you add more elements to them.
ArrayList in Java is used to store dynamically sized collection of elements. Contrary to Arrays that are fixed in size, an ArrayList grows its size automatically when new elements are added to it. ArrayList is part of Java's collection framework and implements Java's List interface.
The array is a fixed sized data structure thus, the array always needs to mention the size of the elements. On the other hand, ArrayList is not a fixed sized data structure, thus there is no need to mention the size of the ArrayList especially creating its object.
An array is faster and that is because ArrayList uses a fixed amount of array. However when you add an element to the ArrayList and it overflows. It creates a new Array and copies every element from the old one to the new one.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With