1. Introduction
Before any type, in go language, we often used interface{} to indicate that a type was unknown or there were several other basic types.
Since Go1.18, go officially defined a predeclared identifier: any.
// any is an alias for interface{} and is equivalent to interface{} in all ways. // any is an alias for interface{} and is the same as interface{} in any case.type any = interface{}
The official definition tells us that any is the alias of interface{}, used to replace interface{}.
Any is also used in the go source code for a lot of time, for example:
func Print(a ...any) (n int, err error) func Println(a ...any) (n int, err error) type Pointer[T any] struct var expunged = new(any) dirty map[any]*entry func Marshal(v any) ([]byte, error) ......
Too many places have been used, basically, go official, and use any instead of any where the interface{} appears.
2. Any's best practices
2.1 In the case of map, map is more suitable for key
Let’s first look at the following two times. Let’s compare which one is better.
func TestAny(t *) { m1 := make(map[any]string, 0) m1["1"] = "1" m1[2] = "2" var v1 string = m1["1"] var v2 string = m1[2] (v1, v2) m2 := make(map[string]any, 0) m2["1"] = "1" m2["2"] = 2 var v3 string = m2["1"].(string) var v4 int = m2["2"].(int) (v3, v4) }
The conclusion is that m1 is good. Why? Because if we use it as a key, we don’t need to do more operations whether we save or read it.
In this way, we need to obtain the data and convert the type. This step is as complicated as it was saved before.
2.2 The parameters and return values of the function, any is more suitable for parameters
In the official json parsing package. Whether it is encoding or decoding, any is just used as a parameter.
func Marshal(v any) ([]byte, error) func Unmarshal(data []byte, v any) error
If it is a return value, we have to call this function and convert the return value type, which is undoubtedly a huge burden for the caller.
But as a parameter, it is a huge convenience for the caller, and it can pass in various types.
The above is a detailed explanation of the use scenario examples of the introduction to go syntax any type. For more information on the use of go syntax any type, please pay attention to my other related articles!