首页 文章

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

提问于
浏览
1

我正在使用https://github.com/kataras/iris golang web框架 . 这是来自上一个问题的跟进邮件 - Fetching Logged in User Info for display - Golang Template

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

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)

我需要在“Type assertion”中为界面提供帮助 . 我如何“键入断言”高于 Value .

请告诉我,正确的方法是什么 . 谢谢

1 回答

  • 2

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

    userID := user.(users).ID
    

    使用它们的类型名称,它应该工作 .

相关问题