小编dar*_*ool的帖子

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

我想将 int 切片作为构造函数的输入,并返回指向原始列表的指针,将类型转换为我的外部自定义类型(type IntList []int)。

我可以做这个:

type IntList []int

func NewIntListPtr(ints []int) *IntList {
    x := IntList(ints)
    return &x
}
Run Code Online (Sandbox Code Playgroud)

但我不能这样做:

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))
}
Run Code Online (Sandbox Code Playgroud)

有没有一条线可以实现这一目标?

casting type-conversion go slice

2
推荐指数
1
解决办法
49
查看次数

标签 统计

casting ×1

go ×1

slice ×1

type-conversion ×1