Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of a Java ArrayList<E> in Golang?

Tags:

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

like image 330
liamzebedee Avatar asked Apr 08 '12 05:04

liamzebedee


People also ask

Is Java ArrayList same as Python list?

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.

What is an ArrayList in Java?

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.

What is difference between array & ArrayList?

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.

Which is better array or ArrayList in Java?

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.


1 Answers

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).

like image 127
Augusto Avatar answered Sep 24 '22 18:09

Augusto