dar*_*ool 2 casting type-conversion go slice
我想将 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)
有没有一条线可以实现这一目标?
你这样做:
func NewIntListPtr(ints []int) *IntList {
return (*IntList)(&ints)
}
Run Code Online (Sandbox Code Playgroud)