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