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
Example to compare Println vs Printf
Golang program for implementation LIFO Stack and FIFO Queue
Example: How to use ReadAtLeast from IO Package in Golang?
How to Improve the Performance of Your Golang Application?
How do you handle HTTP server HTTP/2 in Go?
Go program to find TXT records of a domain