それが第一の方法で呼ばれていた場合、コードは動作しますが、この方法は、別のメソッドを呼び出す場合、コードが失敗しているようです。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
任意の助けをいただければ幸いです!移動中
ポインタ受信機を使用する必要があります。そうしないと、コピーを追加する必要があります。 – Volker