英文:
golang how to access interface fields
问题
我有一个函数,如下所示,它解码一些JSON数据并将其作为接口返回。
package search
func SearchItemsByUser(r *http.Request) interface{} {
type results struct {
Hits hits
NbHits int
NbPages int
HitsPerPage int
ProcessingTimeMS int
Query string
Params string
}
var Result results
er := json.Unmarshal(body, &Result)
if er != nil {
fmt.Println("error:", er)
}
return Result
}
我试图访问数据字段(例如Params),但由于某些原因它说接口没有这样的字段。有任何想法为什么?
func test(w http.ResponseWriter, r *http.Request) {
result := search.SearchItemsByUser(r)
fmt.Fprintf(w, "%s", result.Params)
}
英文:
I have a function as below which decodes some json data and returns it as an interface
package search
func SearchItemsByUser(r *http.Request) interface{} {
type results struct {
Hits hits
NbHits int
NbPages int
HitsPerPage int
ProcessingTimeMS int
Query string
Params string
}
var Result results
er := json.Unmarshal(body, &Result)
if er != nil {
fmt.Println("error:", er)
}
return Result
}
I'm trying to access the data fields ( e.g. Params) but for some reasons it says that the interface has no such field. Any idea why ?
func test(w http.ResponseWriter, r *http.Request) {
result := search.SearchItemsByUser(r)
fmt.Fprintf(w, "%s", result.Params)
答案1
得分: 33
接口变量可以用来存储符合该接口的任何值,并调用该接口的方法。请注意,您无法通过接口变量直接访问底层值的字段。
在这种情况下,您的SearchItemsByUser
方法返回一个interface{}
值(即空接口),它可以保存任何值,但不提供对该值的直接访问。您可以通过类型断言提取接口变量持有的动态值,如下所示:
dynamic_value := interface_variable.(typename)
但在这种情况下,动态值的类型对于您的SearchItemsByUser
方法是私有的。我建议对您的代码进行两个更改:
-
在顶层定义您的
results
类型,而不是在方法体内部。 -
使
SearchItemsByUser
直接返回results
类型的值,而不是interface{}
。
英文:
An interface variable can be used to store any value that conforms to the interface, and call methods that art part of that interface. Note that you won't be able to access fields on the underlying value through an interface variable.
In this case, your SearchItemsByUser
method returns an interface{}
value (i.e. the empty interface), which can hold any value but doesn't provide any direct access to that value. You can extract the dynamic value held by the interface variable through a type assertion, like so:
dynamic_value := interface_variable.(typename)
Except that in this case, the type of the dynamic value is private to your SearchItemsByUser method. I would suggest making two changes to your code:
-
Define your
results
type at the top level, rather than within the method body. -
Make
SearchItemsByUser
directly return a value of theresults
type instead ofinterface{}
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论