2

I am fairly new to Go. I have coded in JavaScript where I could do this:

var x = [];
x[0] = 1;

This would work fine. But in Go, I am trying to implement the same thing with Go syntax. But that doesn't help. I need to have a array with unspecified index number.

I did this:

var x []string
x[0] = "name"

How do I accomplish that?

icza
  • 389,944
  • 63
  • 907
  • 827
camoflage
  • 147
  • 1
  • 5
  • 11
  • 3
    have you gone to [gotour](https://tour.golang.org/welcome/1)? check [this](https://tour.golang.org/moretypes/6) out – stevenferrer Sep 21 '17 at 06:38
  • There's still index number specified. – camoflage Sep 21 '17 at 06:40
  • the syntax that you're using is for slices (dynamic arrays), if you want arrays you would indicate the array size – stevenferrer Sep 21 '17 at 06:41
  • Is there any other way I can store value in array without specifying the value of n when the array is initialized?- thank you – camoflage Sep 21 '17 at 06:41
  • this is how you do it: `arr := [...]string{"foo", "bar"}` provided that the size of array is fixed, means it can't grow or shrink – stevenferrer Sep 21 '17 at 06:43
  • I don't know why I got a negative vote. At least I deserve to know the reason... :( – camoflage Sep 21 '17 at 07:35
  • 2
    @camoflage The downvote was because if you had google "go arrays" the first result would have been the official documentation and if you read it you wouldn't have made this question. You should always try to do some research before asking here. Also when starting with a new language it's important to go through the documentation and try to learn the basics. Go is very well documented and the original authors have written small posts detailing how to use all the basics of the language – Topo Sep 21 '17 at 08:33
  • 1
    @camoflage The best thing you can do when starting to program in go is go through the [tour of go](https://tour.golang.org/welcome/1) it takes like 20 minutes to go through it, and it covers all the basics of the language with examples that you can edit and run right there to get to know the language. [Here](https://blog.golang.org/index) you can find all the blog posts on the go blog. Some of them, specially the old ones, talk about how to best use the language and how to use slices, concurrency, channels, maps, etc.. I really recommend spending a couple of hours just looking around. – Topo Sep 21 '17 at 08:36

5 Answers5

4

When you type:

var x []string

You create a slice, which is similar to an array in Javascript. But unlike Javascript, a slice has a set length and capacity. In this case, you get a nil slice which has the length and capacity of 0.

A few examples of how you can do it:

x := []string{"name"}   // Creates a slice with length 1

y := make([]string, 10) // Creates a slice with length 10
y[0] = "name"           // Set the first index to "name". The remaining 9 will be ""

var z []string          // Create an empty nil slice
z = append(z, "name")   // Appends "name" to the slice, creating a new slice if required

More indepth reading about slices: Go slices usage and internals

ANisus
  • 74,460
  • 29
  • 162
  • 158
1

In JavaScript arrays are dynamic in the sense that if you set the element of an array using an index which is greater than or equal to its length (current number of elements), the array will be automatically extended to have the required size to set the element (so the index you use will become the array's new length).

Arrays and slices in Go are not that dynamic. When setting elements of an array or slice, you use an index expression to designate the element you want to set. In Go you can only use index values that are in range, which means the index value must be 0 <= index < length.

In your code:

var x []string
x[0] = "name"

The first line declares a variable named x of type []string. This is a slice, and its value will be nil (the zero value of all slice types, because you did not provide an initialization value). It will have a length of 0, so the index value 0 is out of range as it is not less that the length.

If you know the length in advance, create your array or slice with that, e.g.:

var arr [3]string           // An array with length of 3
var sli = make([]string, 3) // A slice with length of 3

After the above declarations, you can refer to (read or write) values at indicies 0, 1, and 2.

You may also use a composite literal to create and initialize the array or slice in one step, e.g.

var arr = [3]string{"one", "two", "three"} // Array
var sli = []string{"one", "two", "three"}  // Slice

You can also use the builtin append() function to add a new element to the end of a slice. The append() function allocates a new, bigger array/slice under the hood if needed. You also need to assign the return value of append():

var x []string
x = append(x, "name")

If you want dynamic "arrays" similar to arrays of JavaScript, the map is a similar construct:

var x = map[int]string{}
x[0] = "name"

(But a map also needs initialization, in the above example I used a composite literal, but we could have also written var x = make(map[int]string).)

You may assign values to keys without having to declare the intent in prior. But know that maps are not slices or arrays, maps typically not hold values for contiguous ranges of index keys (but may do so), and maps do not maintain key or insertion order. See Why can't Go iterate maps in insertion order? for details.

Must read blog post about arrays and slices: Go Slices: usage and internals

Recommended questions / answers for a better understanding:

Why have arrays in Go?

How do I initialize an array without using a for loop in Go?

How do I find the size of the array in go

Keyed items in golang array initialization

Are golang slices pass by value?

icza
  • 389,944
  • 63
  • 907
  • 827
0

Can you please use var x [length]string; (where length is size of the array you want) instead of var x []string; ?

dmp
  • 66
  • 9
  • I wouldn't recommend using arrays. It is seldom you work with arrays in go. – ANisus Sep 21 '17 at 06:46
  • length is still a specified value which I have to scecify before the array is initialized, right? – camoflage Sep 21 '17 at 06:49
  • @camoflage Just beware that this answer is about *arrays* and not *slices*. They might look similar in syntax, the only differences being the extra length, but they behave quite different. An array is the underlying "storage" for a slice. – ANisus Sep 21 '17 at 07:00
0

In Go defining a variable like var x=[]int creates a slice of type integer. Slices are dynamic and when you want to add an integer to the slice, you have to append it like x = append(x, 1) (or x = append(x, 2, 3, 4) for multiple).

As srxf mentioned, have you done the Go tour? There is a page about slices.

Postie
  • 324
  • 3
  • 15
-1

I found out that the way to do it is through a dynamic array. Like this

type mytype struct {
  a string
}

func main() {
  a := []mytype{mytype{"name1"}}
  a = append(a, mytype{"name 2"})

fmt.Println(a);
}

golang playground link: https://play.golang.org/p/owPHdQ6Y6e

camoflage
  • 147
  • 1
  • 5
  • 11