2016-11-18 44 views
2

首先,我略高於Go中的初學者,需要一點幫助。 我以爲我已經斷言(據我已經學會了去了),但我不斷收到此錯誤 cannot use readBack["SomePIN"] (type interface {}) as type string in argument to c.String: need type assertion錯誤:需要類型斷言

這裏是我的代碼(該段是從一個請求處理函數和我使用回聲的Web框架和細節一般的NoSQL數據庫)

// To get query result document, simply 
// read it [as stated in the Tiedot readme.md] 
for id := range queryResult { 
    readBack, err := aCollection.Read(id) 
    if err != nil { 
     panic(err) 
    } 
    if readBack["OtherID"] == otherID { 
     if _, ok := readBack["SomePIN"].(string); ok { 
      return c.String(http.StatusOK, readBack["SomePIN"]) 
     } 
    } 
} 

回答

6

您聲稱readBack["SomePIN"]作爲字符串 - 中的if陳述。這並不會對readBack["SomePIN"]做任何修改,但它仍然是一個界面{}。在Go中,沒有什麼會改變類型。這是什麼將工作:

for id := range queryResult { 
    readBack, err := aCollection.Read(id) 
    if err != nil { 
     panic(err) 
    } 
    if readBack["OtherID"] == otherID { 
     if somePIN, ok := readBack["SomePIN"].(string); ok { 
      return c.String(http.StatusOK, somePIN) 
     } 
    } 
} 

你是從你的類型斷言折騰字符串值,但你想要它。所以保留它,如somePIN,然後使用它。

最後注意事項 - 使用value, ok = interfaceVal.(type)語法是一種很好的做法。如果interfaceVal原來是非字符串,則會得到value = ""ok = false。如果您從類型斷言中消除了ok值,並且interfaceVal是非字符串,那麼程序將會出現混亂。

3

它看起來像你轉換到一個具體類型和扔掉的轉換,我認爲這應該工作:

if somePinString, ok := readBack["SomePIN"].(string); ok { 
     return c.String(http.StatusOK, somePinString) 
    }