It is said that interface{}
represents any type in Go. For example, let us consider a Marshal
function in encoding/json
which is used to convert Go data structure into a JSON string. Its definition is
func Marshal(v interface{}) ([]byte, error)
But we are passing a struct to it as a parameter like below.
type hello struct{
Message string
}
data,err:= json.Marshal(hello{Message:'Hello world'})
How is Go handling this?
The answer is runtime reflection.
From docs:
Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types. The typical use is to take a value with static type interface{} and extract its dynamic type information by calling TypeOf, which returns a Type.