golang如何访问接口字段 [英] golang how to access interface fields

查看:30
本文介绍了golang如何访问接口字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下函数,它解码一些 json 数据并将其作为接口返回

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)

推荐答案

接口变量可用于存储符合接口的任何值,并调用作为该接口一部分的方法.请注意,您将无法通过接口变量访问基础值上的字段.

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.

在这种情况下,您的 SearchItemsByUser 方法返回一个 interface{} 值(即空接口),它可以保存任何值但不提供任何直接访问到那个值.您可以通过类型断言提取接口变量持有的动态值,如下所示:

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)

除非在这种情况下,动态值的类型对您的 SearchItemsByUser 方法是私有的.我建议对您的代码进行两项更改:

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:

  1. 在顶层定义您的 results 类型,而不是在方法体内.

  1. Define your results type at the top level, rather than within the method body.

SearchItemsByUser 直接返回 results 类型的值,而不是 interface{}.

Make SearchItemsByUser directly return a value of the results type instead of interface{}.

这篇关于golang如何访问接口字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆