How to create Slice using new keyword in Golang?
A slice can be declare using new keyword followed by capacity in square brackets then type of elements the slice will hold.
Example
package main
import (
"fmt"
"reflect"
)
func main() {
var intSlice = new([50]int)[0:10]
fmt.Println(reflect.ValueOf(intSlice).Kind())
fmt.Printf("intSlice \tLen: %v \tCap: %v\n", len(intSlice), cap(intSlice))
fmt.Println(intSlice)
}
Output
slice
intSlice Len: 10 Cap: 50
[0 0 0 0 0 0 0 0 0 0]
Most Helpful This Week
Golang program for implementation of Selection Sort
How to Iterate Over a Slice in Golang?
Create and Print Multi Dimensional Slice in Golang
Multiple-value <function> in single-value context error in Golang
Go program to find MX records record of a domain
How append a slice to an existing slice in Golang?
Example to compare Println vs Printf
How to convert Struct fields into Map String?
What is Slice Data Type in Go?
Implementing Multiple Interfaces in Go Programming Language