How to create Slice using Make function in Golang?
Slice can be created using the built-in function make. When you use make, one option you have is to specify the length of the slice. When you just specify the length, the capacity of the slice is the same.
Example
package main
import (
"fmt"
"reflect"
)
func main() {
var intSlice = make([]int, 10) // when length and capacity is same
var strSlice = make([]string, 10, 20) // when length and capacity is different
fmt.Printf("intSlice \tLen: %v \tCap: %v\n", len(intSlice), cap(intSlice))
fmt.Println(reflect.ValueOf(intSlice).Kind())
fmt.Printf("strSlice \tLen: %v \tCap: %v\n", len(strSlice), cap(strSlice))
fmt.Println(reflect.ValueOf(strSlice).Kind())
}
Output
intSlice Len: 10 Cap: 10
slice
strSlice Len: 10 Cap: 20
slice
Most Helpful This Week
Creating Instances of Struct Types
How to set timeout for http.Get() requests in Golang?
This sample program demonstrates how to create multiple goroutines and how the goroutine scheduler behaves with three logical processors.
Make Your Retirement Luxurious with These 5 Game-Changing Altcoins
Find odd and even numbers using goroutines and channels
Interface embedding and calling interface methods from another package in Go (Golang)