简体   繁体   English

golang如何访问界面字段

[英]golang how to access interface fields

I have a function as below which decodes some json data and returns it as an interface 我有一个下面的功能,它解码一些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

}

I'm trying to access the data fields ( eg Params) but for some reasons it says that the interface has no such field. 我正在尝试访问数据字段(例如Params),但是由于某些原因,它说该接口没有这样的字段。 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. 请注意,您将无法通过接口变量访问基础值上的字段。

In this case, your SearchItemsByUser method returns an interface{} value (ie the empty interface), which can hold any value but doesn't provide any direct access to that value. 在这种情况下,您的SearchItemsByUser方法将返回interface{}值(即空接口),该值可以保存任何值,但不提供对该值的任何直接访问。 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. 除非在这种情况下,否则动态值的类型是SearchItemsByUser方法专用的。 I would suggest making two changes to your code: 我建议对您的代码进行两项更改:

  1. Define your results type at the top level, rather than within the method body. 在顶层而不是在方法主体中定义results类型。

  2. Make SearchItemsByUser directly return a value of the results type instead of interface{} . 使SearchItemsByUser直接返回results类型的值,而不是interface{}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM