2

So, I'm trying to get used to Go! and I've come up to a problem where I try making a new data type "RandomType" which contains a slice.

package main

type RandomType struct {
    RandomSlice []int
}

func main() {
    r := new(RandomType)
    r.RandomSlice = make([]int, 0)
    append(r.RandomSlice, 5)
}

This bit of code yields an error:

append(r.RandomSlice, 5) not used

However for instance if I try with

type RandomType struct {
    RandomInt int
}

func main() {
    r := new(RandomType)
    r.RandomInt = 5
}

this works fine.

Not sure what I'm doing wrong.

4

1 回答 1

10

append不会更改您提供的切片,而是构建一个新切片。

您必须使用返回的切片:

 r.RandomSlice = append(r.RandomSlice, 5)

有关有效 GoGo 博客中的附加的更多详细信息。

于 2013-07-29T08:26:20.490 回答