DEV Community

Cover image for How to create a slice with the make() function in Go or Golang?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to create a slice with the make() function in Go or Golang?

#go

Originally posted here!

To create a slice in Go or Golang, one way is to use the make() function and pass the type of the slice we need to make as the first argument and the length of the elements that should be created in the slice as the second argument.

package main

import "fmt"

func main(){
    // create a `string` type slice
    // with `5` empty values
    // using the `make()` function
    mySlice := make([]string, 5)

    // print the value of the `mySlice` slice
    fmt.Println(mySlice) // [    ] ✅
}
Enter fullscreen mode Exit fullscreen mode

For example, let's say we need to create a string type slice with 5 empty string values. To do that we can use the make() built-in function and pass the string type slice as the first argument and the number 5 as the second argument.

It can be done like this,

package main

func main(){
    // create a `string` type slice
    // with `5` empty values
    // using the `make()` function
    mySlice := make([]string, 5)
}
Enter fullscreen mode Exit fullscreen mode

Now let's print the output of the mySlice slice to the console like this,

package main

import "fmt"

func main(){
    // create a `string` type slice
    // with `5` empty values
    // using the `make()` function
    mySlice := make([]string, 5)

    // print the value of the `mySlice` slice
    fmt.Println(mySlice) // [    ] ✅
}
Enter fullscreen mode Exit fullscreen mode

As you can see that an empty array with 5 empty values is printed to the console which proves that we have made a string type slice with 5 empty values. Yay 🥳.

See the above code live in The Go Playground.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)