Home  >  Article  >  Backend Development  >  Function in Go that converts an int slice to a custom int slice pointer type

Function in Go that converts an int slice to a custom int slice pointer type

王林
王林forward
2024-02-08 21:33:09521browse

Go 中将 int 切片转换为自定义 int 切片指针类型的函数

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.

Question content

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?

Solution

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete