使用指向切片的指针进行切片操作

huangapple go评论101阅读模式
英文:

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:]...)

huangapple
  • 本文由 发表于 2016年4月25日 21:34:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/36842161.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定