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
What is state in React?
Go program to find Forward(A) record of a domain
GO language program with example of Array Reverse Sort Functions for integer and strings
How do you handle HTTP errors in Go?
Golang Program to print Triangle of Numbers
Polymorphism in Go Programming Language
Interface embedding and calling interface methods from another package in Go (Golang)
Golang program for implementation of Bubble Sort
Print inverted full pyramid using star
Go program to find Name Server (NS) record of a domain