In the last article, you learned the definition of an interface and how to implement one. Next, continue to learn about interfaces.

Empty interface

An empty interface means that there are no constraints, so any type variable can implement an empty interface.

A null interface can represent any data type.

package main

import "fmt"

/ / air interface
type AllType interface{}func main (a) {
    var at AllType
    str := "hello world"
	// Assign STR of string to at of AllType, but it still refers to an instance of string
    at = str
    fmt.Printf("value:%v type:%T\n", at, at) // value:hello world type:string

    num := 32
	Int num is assigned to AllType at, but it still refers to an int
    at = num
    fmt.Printf("value:%v type:%T\n", at, at) // value:32 type:int

    flag := true
	// Flag is assigned to AllType at, but it still refers to bool
    at = flag
    fmt.Printf("value:%v type:%T", at, at) // value:true type:bool 
}
Copy the code

As the code above shows, variables of any type can be assigned to variables of the null interface type. Although variables of empty interface type can accept any type, the actual address referenced by the variable is still the original variable.

Because an empty interface can accept any type, when an empty interface is a function’s argument type, the function’s argument can accept variables of any type as arguments.

Type inference

Type inference can be used to restore an interface variable to its original type or to determine whether a more specific interface type has been implemented.

Type assertion can be used when determining the type of a value in an empty interface

x.(T)
Copy the code
  • X: represents a variable of type interface{}
  • T: indicates the type of assertion x may be
package main
import "fmt"

type animal interface {
    speak() string
}

type bird interface {
    animal
    fly()
}

type Magpie struct{}func(magpie Magpie) speak(a) string {
    return "Chattering"
}

func(magpie Magpie) fly(a) {
    fmt.Println("Fly ~ ~ ~ ~")}func eat(a animal) {
    fmt.Println("Let's go.")}func main(a) {
    var magpie Magpie
    var a animal = magpie
    v, ok := a.(Magpie)
    if ok {
        fmt.Printf("%v is a Magpie \n", v) // {} is a Magpie
    } else {
        fmt.Println("Assertion failed")}}Copy the code

Again, this is illustrated by the previous code example. You can see that the current variable a is an instance of type T by using x.(T).