我正在研究通過UDP接收ascii消息的小型Go程序。我想查看郵件中的第一個字段並查看它是否存在於地圖中。 Go認爲這個關鍵在地圖上不存在,但它確實存在。我可以將密鑰添加到地圖中,並創建一個新條目,所以我有兩個具有相同密鑰的條目。我是我做錯了什麼或者這是一個錯誤?轉到地圖有重複的鍵
編輯: 我簡化了測試,刪除UDP和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: ----------\n%v\n\n", tcmap)
buf := make([]byte, 1024)
buf[0] = 'a'//0x61
buf[1] = 'd'//0x64
buf[2] = 'c'//0x63
fmt.Printf("Received: ---------\n%v\n\n", string(buf[0:3]))
fmt.Printf("Compare hex:-------\n|%x| |%x|\n\n", buf[0:3], "adc")
// Get the first field from the message
testname := strings.Split(strings.Trim(string(buf), " "), " ")[0]
fmt.Printf("Test Name: |%v|\n", testname)
// Does the key exist in the map?
if t, ok := tcmap[testname]; ok {
fmt.Printf("Test found: %v\n", t)
} else {
fmt.Printf("Test NOT found\n")
}
// Add testname to map, does it replace existing?
tcmap[testname] = TestCase{Test: "/foo"}
fmt.Printf("\nMAP: ---------\n%v\n\n", tcmap)
fmt.Printf("KEY adc:---------\n%v\n\n", tcmap["adc"])
for k,v := range tcmap {
fmt.Printf("%v: %v\n", k, v)
}
}
輸出:
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 }
你應該刪除所有UDP和其他與map無關的東西。嘗試提供簡單的代碼示例。 –
嘗試獲取映射中鍵的值並將其與'testname'的值進行比較 - 它們看起來可能相同,但可能不同。例如'adc'和'аdс' - 看起來相似,但有兩個不同的字符。 將您的代碼示例播放到play.golang.org –
感謝您更新代碼示例。但是,第一,你是十六進制而不是地圖鍵。嘗試移動範圍內的十六進制打印。第2位。我想這個問題與你獲得測試名稱的方式有關。嘗試打印len(testname) - 可能的0字節不會打印,所以你認爲它只是'adc',但實際上它是'adc \ x0 \ 0 ....' –