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 关注
- 135 浏览
添加回答
举报