簡體   English   中英

為什么我不能附加到golang中的結構屬性的切片?

[英]Why can't I append to a slice that's the property of a struct in golang?

我正在嘗試將值附加到golang切片,如果在第一個方法中調用它,代碼就可以工作,但如果此方法調用另一個方法,則代碼似乎失敗了。

示例(Test3是我最初嘗試做的):

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(), "\n")

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

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

這輸出:

Test1 final: [0 1] 

Test2 final: [0 1] 

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

游樂場副本: https//play.golang.org/p/upEXINUvNu

任何幫助將不勝感激!

Go中的所有內容都按值傳遞。 並且復制由傳遞的值組成。

Test3.combo()有值(非指針)接收器:

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)
  }
}

這意味着當Test3.combo()是從稱為Test3.run()c.combo()復制由c (其類型的Test3 )。 combo()方法在副本上運行。 它正確地將2個數字附加到Test3.all ,但是當此方法返回時,將丟棄該副本。

因此,當Test3.run()返回c.all ,它返回一個空( nil )切片,因為附加了Test3.combo()的切片是一個副本的字段,並且已被丟棄。

解決方案:只需使用指針接收器:

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

輸出(在Go Playground上試試):

Test1 final: [0 1] 

Test2 final: [0 1] 

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

注意接收器中的星號*func (c *Test3) combo() 通過添加它,你使接收器成為一個指針,所以當調用combo()時,它只接收一個指向Test3類型值的指針,它將修改指向的值, Test3.run()具有的值,所以當combo()返回時,更改不會丟失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM