英文:
Slicing using pointer to a slice
问题
我正在尝试修改另一个函数中的切片,使用以下代码:
type DT struct {
name string
number int
}
func slicer(a *[]DT) {
tmp := *a
var b []DT
b = append(b, tmp[:1]...) // 将tmp[:1]的元素追加到b中
b = append(b, tmp[len(tmp)-1]) // 将tmp的最后一个元素追加到b中
*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)
}
我想要的是切片的第一个和最后一个元素。但是,这样做时,我遇到了以下错误:
cannot use tmp[:1] (type []DT) as type DT in append
我对Go语言相对陌生,所以请指导我解决这个问题!
英文:
I am trying to modify slice a slice in another function, using the following code:
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)
}
What I want is, 1st and last element of the slice. But, in doing so, I am getting following error:
cannot use tmp[:1] (type []DT) as type DT in append
I am relatively new to Go Language, so kindly guide me through this one!
答案1
得分: 5
你应该使用运算符...
将切片转换为可变参数列表。
b = append(b, tmp[:1]...)
b = append(b, tmp[2:]...)
英文:
You should use operator ...
to convert slice into list of variadic arguments.
b = append(b, tmp[:1]...)
b = append(b, tmp[2:]...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论