我遇到了一個問題,即返回的整數值與一組相同,即使在 go 子例程中更新了值之后也是如此。我似乎無法弄清楚出了什么問題。//HostUptimeReporter - structtype HostUptimeReporter struct { updateInterval int uptime int shutdownSignal chan bool}//NewHostUpTimeReporter - create reporter instancefunc NewHostUpTimeReporter(updateIntervalInSeconds int) HostUptimeReporter { instance := HostUptimeReporter{updateInterval: updateIntervalInSeconds, shutdownSignal: make(chan bool), uptime:59} ticker := time.NewTicker(time.Duration(updateIntervalInSeconds) * time.Second) go func() { for { select { case <-ticker.C: instance.uptime += updateIntervalInSeconds fmt.Printf("updated uptime:%v\n", instance.uptime) case <-instance.shutdownSignal: ticker.Stop() return } } }() return instance}//Shutdown - shuts down the go routinefunc (hupr *HostUptimeReporter) Shutdown(){ hupr.shutdownSignal <- true}func main() { hurp := NewHostUpTimeReporter(2) defer hurp.Shutdown() fmt.Printf("current uptime:%v\n", hurp.uptime) time.Sleep(3*time.Second) fmt.Printf("new uptime:%v\n", hurp.uptime)}https://play.golang.org/p/ODjSBb0YugK任何指針表示贊賞。
在 go 例程中更新后未返回更新值
慕碼人8056858
2023-04-17 15:00:35