golang如何访问界面字段 [英] golang how to access interface fields

查看:104
本文介绍了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

}

我试图访问数据字段(例如Params),但由于某些原因说界面没有这样的领域。任何想法为什么?

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)

$ b $一个接口变量可用于存储符合接口的任何值,并调用该接口的艺术部分的方法。

请注意,您将无法通过接口变量访问底层值上的字段。

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:

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

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:

除此之外,动态值的类型对您的SearchItemsByUser方法是私有的。我建议对您的代码进行两处更改:

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


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

  2. 使 SearchItemsByUser 直接返回结果类型的值,而不是界面{}

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

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

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