The Go interface is also called an interface, which defines method names. As mentioned in the second article, this is a highly abstract type that is easy to forget and has some advanced uses that require careful study. Methods are usually declared and implemented using structures (SCtucts), which are used in more detail today

Universal type

The basic data types of the Go language implement interface{}. This means that the empty interface{} can refer to any data type, such as int,string,float, struct. Function parameters can use empty interfaces, and arguments can be of any data type.

package main
import "fmt"
func showAny(mytest interface{}){
	fmt.Println(mytest)   // Print the interface directly
}

func main(a) {
	type user struct{
		name string
	}
	showAny("string test")
	showAny(123)
	showAny(123.456)
	worker :=user{"Earthy excavator"}
	showAny(worker)
}
Copy the code

go run main.goTake a look at the results:As you can see from the results, an empty interface can indeed reference any data type. Isn’t this the concept of polymorphism in the face of three major characteristics of objects: abstraction, inheritance and polymorphism?

Types of assertions

Assertions are colloquially used to determine the type of a variable, and there is a similar procedure for assertions in Gin framework documentation:

binding.Validator.Engine()Is the interface implemented by the third party package, inside*validator.ValidateThis is the validation that the pointer passes.

To implement a simple type assertion, change the code example above, change the contents of the showAny function, and determine what the interface refers to:

package main
import "fmt"

type user struct{
	name string
}
func showAny(mytest interface{}){
	_,ok:=mytest.(string)
	if ok{
		fmt.Printf("%s is: string \n",mytest)
	}
	_,ok=mytest.(int)
	if ok{
		fmt.Printf("%d is: integer \n",mytest)
	}
	_,ok=mytest.(float64)
	if ok{
		fmt.Printf("%g is: float \n",mytest)
	}
	_,ok=mytest.(user)
	if ok{
		fmt.Printf("%s is: user structure \n",mytest)
	}

}

func main(a) {
	showAny("string test")
	showAny(123)
	showAny(123.456)
	worker :=user{"Earthy excavator"}
	showAny(worker)
}
Copy the code

Execution Result:

So usingmytest.(type)If the second parameter is not False, then the assertion is successful. If the second parameter is False, then the statement continues.

conclusion

Before we talked about the common use of interface, can use any defined type to achieve any interface, today we said that the empty interface can reference any type, can also do type assertion, reflects the interface flexible and powerful, reflects the Go language polymorphic characteristics.