How does golang effect reflection?

Using reflection, we can get the type name, storage size, and a function of that type (for example, uint64, user-defined structure, etc.). Even we can modify some fields of this type. How does golang implement reflection? I suggest the following methods:

  • Each golang type, including the user type, itself has information about the type name, field name, and function name. Golang reflection simply reads this information or calls a function.

  • Through some mechanism, Golang can get the type name, storage size, etc. And the type itself does not have this information.

I read the golang reflection code approximately. I guessed that the golang used the second way. Who can describe a specific reflection tool? Or recommend me some documents? Reading all the code is difficult for me.

+5
source share
2 answers

This is just a review, and it may not be 100% accurate, but I hope you find it useful.

At the time of the Go build, the linker will insert information about all types used by the application into the executable file ( https://github.com/golang/go/blob/master/src/runtime/symtab.go#L39 )

Each interface value contains a pointer to a data type descriptor ( https://github.com/golang/go/blob/master/src/runtime/type.go#L14 )

During conversion from a type that is known at compile time, the Go interface value the compiler will point to a type descriptor of this interface value to a specific type descriptor (it is known at compile time!).

eg. when you call reflect.TypeOf(uint(87)) :

  • the value of the interface is created by a compiler that refers to a descriptor of type uint
  • this interface value is passed to the reflect.TypeOf function as an argument. Function
  • reflect.TypeOf uses a type descriptor that was saved by the linker in the executable to obtain alignment information (and another) about the uint type.
+4
source

The description of the interfaces is well described here: Laws of reflection .

An interface type variable holds a pair: a specific value is assigned to a variable and this value type descriptor.

Basically, a type is known statically from your code. More flexible interface types retain the original base type to return to the original data type.

+1
source

Source: https://habr.com/ru/post/1239860/


All Articles