1 回答

TA貢獻1815條經(jīng)驗 獲得超10個贊
您需要執(zhí)行類型斷言:特別是 Effective Go 的這一部分。
str, ok := value.(string)
if ok {
fmt.Printf("string value is: %q\n", str)
} else {
fmt.Printf("value is not a string\n")
}
給出您要執(zhí)行的操作的更精確示例:
if userID, ok := session.Values["userID"].(string); ok {
// User ID is set
} else {
// User ID is not set/wrong type; raise an error/HTTP 500/re-direct
}
type M map[string]interface{}
err := t.ExecuteTemplate(w, "user_form.tmpl", M{"current_user": userID})
if err != nil {
// handle it
}
您所做的是確保您從 interface{} 容器中提取的用戶 ID 實際上是一個字符串。{} 如果不是,你處理它(如果你不這樣做,你會按照文檔編寫程序恐慌)。
如果是,您可以將其傳遞給您的模板,您可以在該模板中將其作為{{ .current_user }}. M是我用來避免每次調(diào)用模板渲染函數(shù)時都必須輸入 map[string]interface{} 的快捷方式。
- 1 回答
- 0 關注
- 463 瀏覽
添加回答
舉報