gpt4 book ai didi

go - 使用指针作为映射键,无法查看是否设置了键

转载 作者:行者123 更新时间:2023-12-01 22:44:48 30 4
gpt4 key购买 nike

我有以下 map :( MyStruct1和MyStruct2是非常大的复杂结构)

faults := make(map[*MyStruct1][]MyStruct2)

我有一个循环遍历 slice 的for循环,第一个检查是查看对象是否存在于映射中:
for _, device := range devices {
for _, drive := range device.Drives {
if !strings.EqualFold(drive.Status, "ONLINE") {
// Check if this is the first fault for this device
if _, set := faults[&device]; !set {
// other stuff snipped for brevity
faults[&device] = make([]MyStruct2, 0)
}
faults[&device] = append(faults[&device], drive)
}
}
}

该检查似乎适用于第一次迭代,但是此检查对于迭代中的每个后续设备均失败。当迭代到下一个设备时,地址是不同的,因此是映射的新密钥...为什么它未能通过此检查?
            if _, set := foo[&device]; !set {
// other stuff snipped for brevity
faults[devicePtr] = make([]MyStruct2, 0)
}

我还尝试了如下检查:
if foo[&device] == nil {
// other stuff snipped for brevity
faults[devicePtr] = make([]MyStruct2, 0)
}

*编辑*
实际上最终只是一个简单的修复。
for i, device := range devices {
devicePtr := &devices[i]
for _, drive := range device.Drives {

然后使用devicePtr作为我的 map 密钥。

谢谢您的帮助。

最佳答案

首先,我更喜欢使用另一个标识符作为映射键。在此示例中,我将device.ID用作 map 密钥

package main

import (
"fmt"
"strings"
)

type Device struct {
ID int64
Drives []Drive
}

type Drive struct {
Name string
Status string
}

func main() {
devices := []Device{
{
ID: 1,
Drives: []Drive{
{
Name: "Drive1.1",
Status: "ONLINE",
},
{
Name: "Drive1.2",
Status: "OFFLINE",
},
},
},
{
ID: 2,
Drives: []Drive{
{
Name: "Drive2.1",
Status: "OFFLINE",
},
{
Name: "Drive2.2",
Status: "OFFLINE",
},
},
},
{
ID: 3,
Drives: []Drive{
{
Name: "Drive3.1",
Status: "OFFLINE",
},
{
Name: "Drive3.2",
Status: "ONLINE",
},
},
},
}

faults := make(map[int64][]Drive)

for _, device := range devices {
for _, drive := range device.Drives {
if !strings.EqualFold(drive.Status, "ONLINE") {
// Check if this is the first fault for this device
if _, set := faults[device.ID]; !set {
// other stuff snipped for brevity
faults[device.ID] = make([]Drive, 0)
}
faults[device.ID] = append(faults[device.ID], drive)
}
}
}

fmt.Printf("%+v", faults)
}

使用这种方法有一些好处:
  • 更快的 map 阅读
  • 更具可读性的代码

  • 但是,如果仍然喜欢使用指针作为 map 键,则应该改为访问 slice 。循环将像这样
    faults := make(map[*Device][]Drive)

    for i := range devices {
    for _, drive := range devices[i].Drives {
    if !strings.EqualFold(drive.Status, "ONLINE") {
    // Check if this is the first fault for this device
    if _, set := faults[&devices[i]]; !set {
    // other stuff snipped for brevity
    faults[&devices[i]] = make([]Drive, 0)
    }
    faults[&devices[i]] = append(faults[&devices[i]], drive)
    }
    }
    }

    关于go - 使用指针作为映射键,无法查看是否设置了键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58306021/

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