編碼時遇到了問題。當我在goroutine中使用內部結構的方法時,我看不到像這個代碼中的內部狀態。去不正確的結構初始化?
package main
import (
"fmt"
"time"
)
type Inner struct {
Value int
}
func (c Inner) Run(value int) {
c.Value = value
for {
fmt.Println(c.Value)
time.Sleep(time.Second * 2)
}
}
type Outer struct {
In Inner
}
func (c Outer) Run() {
go c.In.Run(42)
for {
time.Sleep(time.Second)
fmt.Println(c.In)
}
}
func main() {
o := new(Outer)
o.Run()
}
程序打印:
from inner: {42}
from outer: {0}
from outer: {0}
from inner: {42}
from outer: {0}
from inner: {42}
from outer: {0}
from outer: {0}
也許是指針的問題,但我不知道如何解決它。
感謝您的決心!現在我明白它是如何工作的。現在代碼工作很好。 –