dousi6087 2016-12-09 15:53
浏览 8
已采纳

去地图有重复的钥匙

I'm working on a small Go program that receives an ascii message over UDP. I want to look up the first field in the message and see if it exist in a map. Go thinks the key does not exist in the map but it does. I can add the key to the map and it creates a new entry, so I have two entries with the same key. I'm I doing something wrong or is this a bug?

EDIT: I've simplified the test down to remove the UDP and YAML.

https://play.golang.org/p/2Bg8UjhfWC

package main

import (
    "fmt"
    "strings"
)

type TestCase struct {
    Test string
    Result string
}

func main() {
    tcmap := make(map[string]TestCase)
    tcmap["adc"] = TestCase{Test: "/bar"}
    fmt.Printf("TestMap: ----------
%v

", tcmap)

    buf := make([]byte, 1024)
    buf[0] = 'a'//0x61
    buf[1] = 'd'//0x64
    buf[2] = 'c'//0x63

    fmt.Printf("Received: ---------
%v

", string(buf[0:3]))
    fmt.Printf("Compare hex:-------
|%x| |%x|

", buf[0:3], "adc")

    // Get the first field from the message
    testname := strings.Split(strings.Trim(string(buf), " "), " ")[0]
    fmt.Printf("Test Name: |%v|
", testname)

    // Does the key exist in the map?
    if t, ok := tcmap[testname]; ok {
        fmt.Printf("Test found: %v
", t)
    } else {
        fmt.Printf("Test NOT found
")
    }

    // Add testname to map, does it replace existing?
    tcmap[testname] = TestCase{Test: "/foo"}
    fmt.Printf("
MAP: ---------
%v

", tcmap)
    fmt.Printf("KEY adc:---------
%v

", tcmap["adc"])
    for k,v := range tcmap {
        fmt.Printf("%v: %v
", k, v)
    }
}

Output:

TestMap: ----------
map[adc:{/bar }]

Received: ---------
adc

Compare hex:-------
|616463| |616463|

Test Name: |adc|
Test NOT found

MAP: ---------
map[adc:{/bar } adc:{/foo }]

KEY adc:---------
{/bar }

adc: {/bar }
adc: {/foo }
  • 写回答

2条回答 默认 最新

  • dongqiaogouk86049 2016-12-12 14:00
    关注

    As pointed out by Alexander, the issue is the length between the two keys are different. One key has the length of 3 and the other has the length of 1024. The first three bytes were the same and on the longer key the remaining bytes were 0x00.

    So the string output of the two keys make it appear the two are identical, but this was fooling me. The length of the keys was different.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码