Home > Article > Backend Development > Function in Go that converts an int slice to a custom int slice pointer type
What php editor Xinyi will introduce to you today is a function that converts int slices into custom int slice pointer types in the Go language. In the Go language, slice is a very commonly used data type that can dynamically increase or decrease the number of elements. Sometimes we need to convert a slice to a custom slice pointer type for operation in a function. This article will describe in detail how to achieve this conversion and give sample code for reference. Through studying this article, I believe that everyone will have a deeper understanding of the use of slices in the Go language.
I want to take an int slice as input to the constructor and return a pointer to the original list, typecasting to my external custom type (type intlist [ ]int
).
I can do this:
type intlist []int func newintlistptr(ints []int) *intlist { x := intlist(ints) return &x }
But I can't do this:
type IntList []int func NewIntListPtr(ints []int) *IntList { return &ints } // or this for that matter: func NewIntListPtr(ints []int) *IntList { return &(IntList(ints)) } // or this func NewIntListPtr(ints []int) *IntList { return &IntList(*ints) } // or this func NewIntListPtr(ints *[]int) *IntList { return &(IntList(*ints)) }
Is there a sentence that can achieve this?
You do this:
func NewIntListPtr(ints []int) *IntList { return (*IntList)(&ints) }
The above is the detailed content of Function in Go that converts an int slice to a custom int slice pointer type. For more information, please follow other related articles on the PHP Chinese website!