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) // [ ] ✅
}
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)
}
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) // [ ] ✅
}
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 😃!