类型接口{}是没有方法的接口 - Golang

时间:2017-09-13 23:21:18

标签: go

我使用的是https://github.com/kataras/iris golang网络框架。这是来自上一个问题的后续邮件 - Fetching Logged in User Info for display - Golang Template

我终于使用上一篇文章中提到的代码,如: -

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

并且用户设置或拥有的值是" Struct"类型: -

// 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)

我需要帮助"输入断言"用于界面。我怎样才能打断断言"高于价值。

请告诉我,正确的做法是什么。 感谢

1 个答案:

答案 0 :(得分:4)

A type assertion就是这样,断言一个值是给定的类型

userID := user.(users).ID

使用它们的类型名称,它应该可以工作。