dongluo8303 2017-02-16 12:39
浏览 293
已采纳

为什么我不能在golang中追加属于结构的属性的切片?

I'm trying to append a value to a golang slice, the code works if it's called in the first method, but if this method calls another method, the code seems to fail.

Examples (Test3 is what I was originally trying to do):

package main

import (
  "fmt"
)

// This works

type Test1 struct {
  all []int
}

func (c Test1) run() []int {
  for i := 0; i < 2; i++ {
    c.all = append(c.all, i)
  }
  return c.all
}

// This works

var gloabl_all []int

type Test2 struct {}

func (c Test2) run() []int {
  c.combo()
  return gloabl_all
}

func (c Test2) combo() {
  for i := 0; i < 2; i++ {
    gloabl_all = append(gloabl_all, i)
  }
}

// This doesn't

type Test3 struct {
  all []int
}

func (c Test3) run() []int {
  c.combo()
  return c.all
}

func (c Test3) combo() {
  for i := 0; i < 2; i++ {
    c.all = append(c.all, i)
    fmt.Println("Test3 step", i + 1, c.all)
  }
}

func main() {
  test1 := &Test1{}
  fmt.Println("Test1 final:", test1.run(), "
")

  test2 := &Test2{}
  fmt.Println("Test2 final:", test2.run(), "
")

  test3 := &Test3{}
  fmt.Println("Test3 final:", test3.run())
}

This outputs:

Test1 final: [0 1] 

Test2 final: [0 1] 

Test3 step 1 [0]
Test3 step 2 [0 1]
Test3 final: []

Playground copy: https://play.golang.org/p/upEXINUvNu

Any help would be greatly appreciated!

  • 写回答

1条回答 默认 最新

  • doubao6464 2017-02-16 12:44
    关注

    Everything in Go is passed by value. And a copy is made of the passed value.

    Test3.combo() has value (non-pointer) receiver:

    func (c Test3) run() []int {
      c.combo()
      return c.all
    }
    
    func (c Test3) combo() {
      for i := 0; i < 2; i++ {
        c.all = append(c.all, i)
        fmt.Println("Test3 step", i + 1, c.all)
      }
    }
    

    This means when Test3.combo() is called from Test3.run() like c.combo(), a copy is made of c (which is of type Test3). The combo() method operates on a copy. It properly appends 2 numbers to Test3.all, but when this method returns, the copy is discarded.

    So when Test3.run() returns c.all, it returns an empty (nil) slice, because the slice to which Test3.combo() appended, was a field of a copy, and which has been discarded.

    Solution: simply use a pointer receiver:

    func (c *Test3) combo() {
      for i := 0; i < 2; i++ {
        c.all = append(c.all, i)
        fmt.Println("Test3 step", i + 1, c.all)
      }
    }
    

    Output (try it on the Go Playground):

    Test1 final: [0 1] 
    
    Test2 final: [0 1] 
    
    Test3 step 1 [0]
    Test3 step 2 [0 1]
    Test3 final: [0 1]
    

    Note the star * in the receiver: func (c *Test3) combo(). By adding it, you make the receiver a pointer, and so when combo() is called, it only receives a pointer to a value of type Test3, and it will modify the pointed value, the value that Test3.run() has, so when combo() returns, the changes are not lost.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能