2016-12-09 35 views
-3

我正在研究通過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 } 
+1

你應該刪除所有UDP和其他與map無關的東西。嘗試提供簡單的代碼示例。 –

+4

嘗試獲取映射中鍵的值並將其與'testname'的值進行比較 - 它們看起來可能相同,但可能不同。例如'adc'和'аdс' - 看起來相似,但有兩個不同的字符。 將您的代碼示例播放到play.golang.org –

+0

感謝您更新代碼示例。但是,第一,你是十六進制而不是地圖鍵。嘗試移動範圍內的十六進制打印。第2位。我想這個問題與你獲得測試名稱的方式有關。嘗試打印len(testname) - 可能的0字節不會打印,所以你認爲它只是'adc',但實際上它是'adc \ x0 \ 0 ....' –

回答

2

正如Alexander指出的那樣,問題在於兩個鍵之間的長度是不同的。一個密鑰的長度爲3,另一個長度爲1024.前三個字節相同,而較長的密鑰的剩餘字節爲0x00。

所以兩個鍵的字符串輸出顯示兩個是相同的,但這是愚弄我。鑰匙的長度不同。

1

的關鍵之一具有一個尾隨換行符。如果您使用strings.TrimSpace而不是strings.Trim,則會看到尾隨的換行符被修剪並且沒有重複。

+0

如果使用TrimSpace,它仍然不起作用。沒有換行符。問題是兩個鍵之間的字節數是不同的。 – dangeroushobo

+0

是的,這是真的...... upvoted你的回答:)(TrimSpace _did_爲我工作......也許這是一個僥倖,我的測試運行額外的字節是新行) –