Please consider the code https://play.golang.org/p/aO07_PoQLuh
I've a list of structs, which I read from to get an idea of the members I've generated enroute.
For each struct, I've a method to raise a counter, however I am missing the sauce here. As you can see from the o/p, I've incremented SBytesSent
, but when I read the list of struct and inspect it, it is at 0.
What's the best way to handle this? Thanks!
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 += 1
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, _ := range destination_list {
dest := destination_list[i]
dest.incrementSBytes(33)
}
}
func status() {
for i, _ := range destination_list {
dest := destination_list[i]
dest.Status()
}
}
Edit 1
Please see https://play.golang.org/p/5uqqc3OKYDs - I've incremented host3
to 6
- yet towards the end they all show 99
. How can I make host3 retain the previous increment and show 99 + 6 = 105
?