Type interface {}是没有方法的接口。

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年9月14日 07:21:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/46208216.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定