DEV Community

Cover image for How to create a fixed-size array in Go or Golang?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to create a fixed-size array in Go or Golang?

#go

Originally posted here!

To create a fixed-size array in Go or Golang, you need to write the [] symbol (square brackets), and inside the brackets, you have to write the number of items you wish to store in the array. After the square brackets symbol, you have to specify the type of elements that you wish to store in the array followed by the {} symbol (curly brackets).

TL;DR

package main

import "fmt"

func main(){
    // create an array of `string`
    // type that can hold `5` items
    // and add a few names to it
    names := [5]string{"John Doe", "Lily Doe", "Roy Doe"}

    // log to the console
    fmt.Println(names) // [John Doe Lily Doe Roy Doe]
}
Enter fullscreen mode Exit fullscreen mode

For example, let's say you need to create an array of names and should hold only 5 items in the array.

To do that, first, we can write the [] symbol (square brackets) and inside the brackets, we can specify the number of items that we wish to hold in the array, which is the number 5 then the write type of the elements in the array which is the type of string without any whitespace followed by the {} symbol (curly brackets).

It can be done like this,

package main

func main(){
    // create an array of `string`
    // type that can hold `5` items
    [5]string{}
}
Enter fullscreen mode Exit fullscreen mode

Now let's assign the array to a variable called names like this,

package main

func main(){
    // create an array of `string`
    // type that can hold `5` items
    names := [5]string{}
}
Enter fullscreen mode Exit fullscreen mode

To add items to the array, we can simply add the string type elements inside the {} symbol separated by the , symbol (comma).

It can be done like this,

package main

func main(){
    // create an array of `string`
    // type that can hold `5` items
    // and add a few names to it
    names := [5]string{"John Doe", "Lily Doe", "Roy Doe"}
}
Enter fullscreen mode Exit fullscreen mode

Finally, let's print the names array to the console to see the added array elements.

It can be done like this,

package main

import "fmt"

func main(){
    // create an array of `string`
    // type that can hold `5` items
    // and add a few names to it
    names := [5]string{"John Doe", "Lily Doe", "Roy Doe"}

    // log to the console
    fmt.Println(names) // [John Doe Lily Doe Roy Doe]
}
Enter fullscreen mode Exit fullscreen mode

As you can see that the names have been logged to the console which proves that the names array is successfully created.

See the above code live in The Go Playground.

That's all 😃.

Feel free to share if you found this useful 😃.


Top comments (0)