This is a creation in Article, where the information may have evolved or changed.
In Golang interface{} can be used to pass a variable of any type to a function, but used inside a function, the type of the variable is interface{}, also known as an empty interface type
For example, we define a function, output a string, but the argument is interface{} type
func echoString(content interface{}) { fmt.Println(content )}
When we call echoString("输出字符串") the method, we get content an error because it's a interface{} type, not a string type.
The conversion of an interface type to a normal type is called a type assertion (run-time determination)
For the above call, you can modify the method byechoString
func echoString(content interface{}) { result, _ := content.(string) //通过断言实现类型转换 fmt.Println(result)}
This time there will be a potential threat, if we give the method is the int type, then we 断言 will be error, this time we need to perfect the code
func echoString(content interface{}) { result, err := content.(string) if err != nil { // 断言失败 fmt.Println(err .Error()) // 输出失败原因 return } fmt.Println(result)}
Operations of different types of variables must be explicitly type-cast, and the result may be error-