Answer the question
In order to leave comments, you need to log in
Go reflection interface{}?
While learning Go, I ran into such a problem - I can’t understand how a language with static typing supports things like reflection?
It is at the system level.
Here is an example: An
unknown JSON arrives to us. In theory, we should create a structure with the fields that we expect in JSON, and only then parse it.
BUT
the option is possible:
var f interface{}
err := json.Unmarshal(inputJSON, &f)
Magic, of course, does not happen, but I would be grateful if someone explains.
Thank you!
Answer the question
In order to leave comments, you need to log in
Go is a relatively loosely typed language. C is a weak type system. Haskell is strongly typed by the complete Hindley-Milner system. In C, anything can be passed by a pointer, and in this sense, any code can be written generic, but unsafe, reflection is impossible. In Haskell, everything is typed at compile time. Typechecker Haskell is a full-fledged Turing Machine, any code is generic and safe at the same time, so reflection is simply not needed. Go is a pragmatic compromise, the type being passed may not be known at compile time but is always known at run time. In Go, the runtime always knows the type of all data from here and beyond this reflection.
For the best example of serialization, consider ffjson . Usually, the fields of the structure and their annotations are read by reflection and then cached them, ffjson, on the contrary, goes through code generation. In some cases (using interfaces in structures) this approach can be even slower than the native Marshal(), and for most applications, even using SIMD instructions with SSE4 or SSE2 when working with strings, it turns out relatively quickly. It is also worth looking at the gob encoder and decoder sources and reading the article .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question