切片:在结构体中追加切片时出现问题

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

Slices: Trouble appending to a slice in a struct

问题

所以,我正在尝试适应Go!我遇到了一个问题,我试图创建一个包含切片的新数据类型"RandomType"。

  1. package main
  2. type RandomType struct {
  3. RandomSlice []int
  4. }
  5. func main() {
  6. r := new(RandomType)
  7. r.RandomSlice = make([]int, 0)
  8. append(r.RandomSlice, 5)
  9. }

这段代码会产生一个错误:

  1. append(r.RandomSlice, 5)未被使用

然而,如果我尝试使用以下代码:

  1. type RandomType struct {
  2. RandomInt int
  3. }
  4. func main() {
  5. r := new(RandomType)
  6. r.RandomInt = 5
  7. }

这段代码可以正常工作。

不确定我做错了什么。

英文:

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.

  1. package main
  2. type RandomType struct {
  3. RandomSlice []int
  4. }
  5. func main() {
  6. r := new(RandomType)
  7. r.RandomSlice = make([]int, 0)
  8. append(r.RandomSlice, 5)
  9. }

This bit of code yields an error:

  1. append(r.RandomSlice, 5) not used

However for instance if I try with

  1. type RandomType struct {
  2. RandomInt int
  3. }
  4. func main() {
  5. r := new(RandomType)
  6. r.RandomInt = 5
  7. }

this works fine.

Not sure what I'm doing wrong.

答案1

得分: 10

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

你必须使用返回的切片:

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

有关append的更多详细信息,请参阅Effective GoGo博客

英文:

append doesn't change the slice you provide but builds a new one.

You must use the returned slice :

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

More details about append in Effective Go and in the Go blog.

huangapple
  • 本文由 发表于 2013年7月29日 16:22:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/17919192.html
匿名

发表评论

匿名网友

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

确定