golang如何访问界面字段

编程入门 行业动态 更新时间:2024-10-22 10:51:55
本文介绍了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方法是私有的。我建议对您的代码进行两处更改:

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

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

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

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

    更多推荐

    golang如何访问界面字段

    本文发布于:2023-07-30 00:35:14,感谢您对本站的认可!
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:字段   界面   golang

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!