Golang如何访问接口字段

huangapple go评论96阅读模式
英文:

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方法是私有的。我建议对您的代码进行两个更改:

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

  2. 使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:

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

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

huangapple
  • 本文由 发表于 2014年2月15日 18:13:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/21796151.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定