gpt4 book ai didi

go - 使用指向 slice 的指针 slice

转载 作者:IT王子 更新时间:2023-10-29 01:52:40 26 4
gpt4 key购买 nike

我正在尝试使用以下代码在另一个函数中修改 slice :

type DT struct {
name string
number int
}

func slicer(a *[]DT) {
tmp := *a
var b []DT
b = append(b, tmp[:1], tmp[2:])
*a = b
}

func main() {
o1 := DT {
name: "name-1",
number: 1,
}
o2 := DT {
name: "name-2",
number: 2,
}
o3 := DT {
name: "name-3",
number: 3,
}

b := make([]DT, 0)
b = append(b, o1)
b = append(b, o2)
b = append(b, o3)

slicer(&b)
fmt.Println(b)
}

我想要的是 slice 的第一个也是最后一个元素。但是,这样做时,我收到以下错误:

cannot use tmp[:1] (type []DT) as type DT in append

我对 Go 语言比较陌生,所以请指导我完成这个!

最佳答案

您应该使用运算符 ... 将 slice 转换为可变参数列表。

 b = append(b, tmp[:1]...)
b = append(b, tmp[2:]...)

关于go - 使用指向 slice 的指针 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36842161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com