英文:
Type interface {} is interface with no methods
问题
我正在使用https://github.com/kataras/iris Golang Web框架。这是对上次在这里提出的问题的跟进邮件-https://stackoverflow.com/questions/46130446/fetching-logged-in-user-info-for-display-golang-template
我最终使用了在之前的帖子中提到的代码,如下所示:
ctx.Values().Get("user")
并且用户设置或拥有的值是"Struct"类型:
// users是下面的结构体
var user users
// 从数据库中获取详细信息并分配给用户
// 如此处所述http://go-database-sql.org/retrieving.html
// 现在值已设置
ctx.Values().Set("user", user);
但是在获取值之后,当我在不同的处理程序中使用并打印时:
user := ctx.Values().Get("user")
fmt.Println(user.ID)
我得到了错误:
user.ID未定义(类型interface {}是没有方法的接口)
我需要在接口中进行"类型断言"方面的帮助。如何对上述值进行"类型断言"?
英文:
I am using https://github.com/kataras/iris golang web framework. This is follow up mail from the last question asked here - https://stackoverflow.com/questions/46130446/fetching-logged-in-user-info-for-display-golang-template
I am finally using code that was mentioned in the previous post like:-
ctx.Values().Get("user")
and the value that user is set or has is "Struct" type:-
// 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);
But after getting the value, When I use in different handler and print:-
user := ctx.Values().Get("user")
fmt.Println(user.ID)
I get the error:-
user.ID undefined (type interface {} is interface with no methods)
I need help in "Type assertion" for the interface. How can I "type assert" above value?
答案1
得分: 7
一个type assertion就是这样,它断言一个值是给定的类型。
userID := user.(users).ID
使用类型名称,它应该可以工作。
英文:
A type assertion does just that, asserts a value is a given type.
userID := user.(users).ID
Use they type name, and it should work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论