Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Go, which value’s kind is reflect.Interface?

Tags:

reflection

go

j:=1

Kind of j is reflect.Int, as expected.

var j interface{} = 1

Kind of j is also reflect.Int.

Which value’s kind is reflect.Interface?

like image 270
lianggo Avatar asked Aug 19 '13 03:08

lianggo


People also ask

What is reflection interface?

Interfaces store type information when assigned a value. Reflection is a method of examining type and value information at runtime. Go implements reflection with the reflect package which provides types and methods for inspecting portions of the interface structure and even modifying values at runtime.

Does Golang have reflection?

Reflection is the ability of a program to introspect and analyze its structure during run-time. In Go language, reflection is primarily carried out with types. The reflect package offers all the required APIs/Methods for this purpose.

What is reflect package in Golang?

Reflection in Go is a form of metaprogramming. Reflection allows us to examine types at runtime. It also provides the ability to examine, modify, and create variables, functions, and structs at runtime. The Go reflect package gives you features to inspect and manipulate an object at runtime.

What is reflect indirect?

The reflect. Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v. To access this function, one needs to imports the reflect package in the program.


1 Answers

If you're looking for a practical solution, the answer is simple and annoying. reflect.TypeOf takes an empty interface type into which you put whatever data you want to pass. The problem with this is that an interface type can't hold another interface type, which means that you effectively can't pass an interface to reflect.TypeOf. There is a workaround, but it's a bit painful. What you have to do is make a composite type (like a struct or slice or map) where one of the element types is an interface type, and extract it. For example:

var sliceOfEmptyInterface []interface{}
var emptyInterfaceType = reflect.TypeOf(sliceOfEmptyInterface).Elem()

That first creates a reflect.Type representation of []interface{} (a slice of interface{} types) and then extracts the element type, which is interface{}.

Courtesy of this post.

like image 130
joshlf Avatar answered Sep 20 '22 05:09

joshlf