2017-09-13 36 views
0

我正在使用https://github.com/kataras/iris golang web框架。這是最後一個問題問這裏跟進郵件 - Fetching Logged in User Info for display - Golang Template類型interface {}是沒有方法的接口 - Golang

我終於用代碼,在以前的帖子就像提到: -

ctx.Values().Get("user")

和用戶設置或具有價值是「結構」類型: -

// users is struct below 

var user users 

// details are fetched from DB and assigned to user 
// like mentioned here http://go-database-sql.org/retrieving.html 
// Now value is set 
ctx.Values().Set("user", user); 

但所獲得的價值後,當我在不同的處理程序和打印使用: -

user := ctx.Values().Get("user") 
fmt.Println(user.ID) 

我得到的錯誤: -

user.ID undefined (type interface {} is interface with no methods)

我需要在 「類型斷言」 爲界面幫助。我怎樣才能「鍵入斷言」以上價值。

請讓我知道,什麼是正確的做法。 謝謝

+0

[Golang類型接口{}的可能重複是沒有方法的接口](https://stackoverflow.com/questions/32277884/golang-type-in​​terface-is-interface-with-no-methods) –

回答

2

A type assertion只是這樣做,斷言值是給定類型

userID := user.(users).ID 

使用它們鍵入名稱,它應該工作。