DEV Community

Cover image for How to create a slice or a dynamic array in Golang or Go?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to create a slice or a dynamic array in Golang or Go?

#go

Originally posted here!

To create a dynamic array or a slice in Golang or Go, we can use the [] symbol (opening and closing square brackets) and then write the value type of the contents that should be in the dynamic array followed by the {} symbol (opening and closing curly brackets) and finally inside {} symbol we can write the values separated by the , symbol (comma).

TL;DR

package main

import "fmt"

func main() {
    // a simple slice or dynamic array that can
    // hold `string` type values in go
    myArr := []string{
        "John", "Lily", "Roy",
    }

    // print the `myArr` silce
    // values to the console
    fmt.Print(myArr) // [John Lily Roy]
}
Enter fullscreen mode Exit fullscreen mode

For example, let's say we need to make a dynamic array called myArr of string type value.

It can be done like this,

package main

func main(){
    // a simple slice or dynamic array that can
    // hold `string` type values in go
    myArr := []string{}
}
Enter fullscreen mode Exit fullscreen mode

Now let's put some string type values inside the slice. The values are separated by the , symbol (comma).

It can be done like this,

package main

func main(){
    // a simple slice or dynamic array that can
    // hold `string` type values in go
    myArr := []string{
        "John", "Lily", "Roy",
    }
}
Enter fullscreen mode Exit fullscreen mode

NOTE: You may have to add the comma for the last value in the slice, or the Golang compiler might throw you an error. In our case, we have added a comma , after the value of Roy in the slice.

Finally, let's print the values in the myArr slice using the Print() method from the fmt module like this,

package main

import "fmt"

func main() {
    // a simple slice or dynamic array that can
    // hold `string` type values in go
    myArr := []string{
        "John", "Lily", "Roy",
    }

    // print the `myArr` silce
    // values to the console
    fmt.Print(myArr) // [John Lily Roy]
}
Enter fullscreen mode Exit fullscreen mode

We have successfully created a silce or a dynamic array in Golang. Yay 🥳.

See the above code live in The Go Playground.

That's all 😃!

Feel free to share if you found this helpful 😃.


Top comments (0)