gpt4 book ai didi

go - 迭代结构列表并更改成员变量

转载 作者:行者123 更新时间:2023-12-01 22:38:14 25 4
gpt4 key购买 nike

请考虑代码https://play.golang.org/p/aO07_PoQLuh

我有一个结构体列表,我从中读取了这些结构体,以了解我在途中生成的成员。

对于每个结构,我都有一种提高计数器的方法,但是我想念这里的内容。从o / p中可以看到,我增加了SBytesSent,但是当我阅读struct列表并检查它时,它为0。

处理此问题的最佳方法是什么?谢谢!

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()
}
}

编辑1

请参阅 https://play.golang.org/p/5uqqc3OKYDs-我已将 host3递增为 6-但最后它们都显示 99。如何使host3保留先前的增量并显示 99 + 6 = 105

最佳答案

它不起作用,因为您正在复制并修改副本:

dest := destination_list[i]
dest.incrementSBytes(33)

在上面,您首先将array元素复制到 dest,然后修改 dest。数组元素永远不会改变。而是尝试以下方法:
destination_list[i].incrementsSBytes(33)

关于go - 迭代结构列表并更改成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59260640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com