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

王林
Release: 2024-02-08 21:33:09
forward
509 people have browsed it

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
}
Copy after login

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))
}
Copy after login

Is there a sentence that can achieve this?

Solution

You do this:

func NewIntListPtr(ints []int) *IntList {
    return (*IntList)(&ints)
}
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!