2 回答

TA貢獻1851條經驗 獲得超5個贊
它不起作用,因為您正在復制并修改副本:
dest := destination_list[i] dest.incrementSBytes(33)
上面,您首先將數組元素復制到dest
,然后修改dest
。數組元素永遠不會改變。而是嘗試這個:
destination_list[i].incrementsSBytes(33)

TA貢獻1830條經驗 獲得超9個贊
所有的魔力都在于range
,它創建該元素的副本,因此修改是不可見的。
package main
import (
? ? "fmt"
? ? "sync"
)
type destination struct {
? ? Name? ? ? ? ? string
? ? SBytesSent? ? int64
? ? ABytesSent? ? int64
? ? LastSeenAlive int64
? ? Mutex? ? ? ? ?*sync.Mutex
}
type destinations []destination
var (
? ? destination_list destinations
? ? myHosts? ? ? ? ? = []string{"host1", "host2", "host3"}
)
func main() {
? ? fmt.Println("Hello, playground")
? ? for i := range myHosts {
? ? ? ? newDest := myHosts[i]
? ? ? ? newd := destination{Name: newDest}
? ? ? ? newd.Mutex = &sync.Mutex{}
? ? ? ? destination_list = append(destination_list, newd)
? ? }
? ? i := 0
? ? for {
? ? ? ? increment()
? ? ? ? status()
? ? ? ? i++
? ? ? ? if i == 3 {
? ? ? ? ? ? break
? ? ? ? }
? ? }
}
func (self *destination) incrementSBytes(a int) {
? ? self.Mutex.Lock()
? ? defer self.Mutex.Unlock()
? ? self.SBytesSent += int64(a)
? ? fmt.Printf("new val %d\n", self.SBytesSent)
}
func (self *destination) Status() {
? ? fmt.Printf("my val %d\n", self.SBytesSent)
}
func increment() {
? ? for i:=0; i<len(destination_list); i++ {
? ? ? ? destination_list[i].incrementSBytes(33)
? ? }
}
func status() {
? ? for i:=0; i<len(destination_list); i++ {
? ? ? ? destination_list[i].Status()
? ? }
}
輸出:
Hello, playground
new val 33
new val 33
new val 33
my val 33
my val 33
my val 33
new val 66
new val 66
new val 66
my val 66
my val 66
my val 66
new val 99
new val 99
new val 99
my val 99
my val 99
my val 99
- 2 回答
- 0 關注
- 196 瀏覽
添加回答
舉報