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

标签 go

请考虑代码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/

相关文章:

string - 使用 String() 方法的 Go 接口(interface)

go - 等待多个协程的结果

go - Hyperledger Fabric Chaincode 在执行期间面临错误

arrays - 使用正则表达式拆分字符串以将子字符串存储在映射中的分隔符内以创建键值对

google-app-engine - 在命令行构建但无法构建为 gae 应用程序

xml - 制作 xml 以在 golang 后的 http 中发送

golang 运行时包从构建它的系统设置文件路径

go - 返回结构指针的函数作为返回接口(interface)的函数

amazon-web-services - 在 Go 中测试 lambda 处理程序时如何模拟 AWS Lambda 上下文?

dictionary - 定义 map slice 的 map 时,出现 “assignment to nil”错误,我是否要即时填充或生成 key ?