1. Empty interface
An interface in Golang can not define any method, and an interface without any method is an empty interface. An empty interface means that there are no constraints, so any type of variable can implement an empty interface. There are many empty interfaces used in actual projects. Using empty interfaces can represent any data type.
func main() { // Define an empty interface x, x variable can receive any data typevar x interface{} s := "Hello golang" x = s ("type:%T value:%v\n", x, x) i := 100 x = i ("type:%T value:%v\n", x, x) b := true x = b fmt
1. Empty interface as a function parameter: Use an empty interface to implement the function parameters of any type.
// Empty interface as function parameterfunc show(a interface{}) { ("type:%T value:%v\n", a, a) }
2. The value of map Implementing an empty interface: Use an empty interface to implement a dictionary that can save any value
// The empty interface is used as the map valuevar studentInfo = make(map[string]interface{}) studentInfo["name"] = "Zhang San" studentInfo["age"] = 18 studentInfo["married"] = false (studentInfo
3. Slicing implements empty interface
var slice = []interface{}{"Zhang San", 20, true, 32.2} (slice)
2. Type Assertion
The value of an interface (referred to as an interface value) is composed of two parts: a specific type and a specific type of value. These two parts
Also known as dynamic types and dynamic values of interfaces.
If we want to determine the type of value in an empty interface, then we can use type assertion at this time, and its syntax format is: x.(T)
in:
• x: represents a variable of type interface{}
• T: indicates the type that asserts that x may be.
This syntax returns two parameters. The first parameter is a variable converted to a T type and the second value is a Boolean value.
If true, it means that the assertion is successful, if false, it means that the assertion fails.
For example:
func main() { var x interface{} x = "Hello golnag" v, ok := x.(string) if ok { (v) } else { ("Type assertion failed") } }
In the above example, if you want to assert multiple times, you need to write multiple if judgments. At this time, we can use the switch statement to
accomplish:
Note: Type.(type) can only be used in combination with switch statements
func justifyType(x interface{}) { switch v := x.(type) { case string: ("x is a string,value is %v\n", v) case int: ("x is a int is %v\n", v) case bool: ("x is a bool is %v\n", v) default: ("unsupport type!") } }
Because empty interfaces can store the characteristics of any type of value, empty interfaces are widely used in the Go language.
What should be noted about the interface is: : Only when there are two or more specific types that must be processed in the same way
Only then do you need to define an interface. Don't write interfaces for the sake of interfaces, as this will only add unnecessary abstraction and lead to unnecessary operation.
time loss.
3. The difference between the structure value receiver and the pointer receiver implementing interface
Value Receiver:
If the method in the structure is the value receiver, then the instantiated structure value type and structure pointer type can be assigned
Value to interface variable
package main import "fmt" type Usb interface { Start() Stop() } type Phone struct { Name string } func (p Phone) Start() { (, "Get Started Work") } func (p Phone) Stop() { ("phone stop") } func main() { phone1 := Phone{ Name: "Xiaomi Mobile", } var p1 Usb = phone1 //phone1 implements the Usb interface phone1 is the Phone type() //Xiaomi mobile phone starts workingphone2 := &Phone{ Name: "Apple phone", } var p2 Usb = phone2 //phone2 implements the Usb interface phone2 is the *Phone type() //Apple phone starts working}
Pointer Receiver:
If the method in the structure is the pointer receiver, then the structure pointer type can be assigned to the interface variable after instantiation.
Structural value type cannot be assigned to interface variables
package main import "fmt" type Usb interface { Start() Stop() } type Phone struct { Name string } func (p *Phone) Start() { (, "Get Started Work") } func (p *Phone) Stop() { ("phone stop") } func main() { /* Wrong writing phone1 := Phone{ Name: "Xiaomi Mobile", } var p1 Usb = phone1 () */ //Correct writingphone2 := &Phone{ Name: "Apple phone", } var p2 Usb = phone2 //phone2 implements the Usb interface phone2 is the *Phone type() //Apple phone starts working}
4. A structure implements multiple interfaces
A structure in Golang can also implement multiple interfaces
package main import "fmt" type AInterface interface { GetInfo() string } type BInterface interface { SetInfo(string, int) } type People struct { Name string Age int } func (p People) GetInfo() string { return ("Name:%v Age:%d", , ) } func (p *People) SetInfo(name string, age int) { = name = age } func main() { var people = &People{ Name: "Zhang San", Age: 20, } // People implement AInterface and BInterfacevar p1 AInterface = people var p2 BInterface = people (()) ("Li Si", 30) (()) }
5. Interface nesting
New interfaces can be created through nesting between interfaces
package main import "fmt" type SayInterface interface { say() } type MoveInterface interface { move() } // Nesting of interfacestype Animal interface { SayInterface MoveInterface } type Cat struct { name string } func (c Cat) say() { ("Meow Meow") } func (c Cat) move() { ("The cat will move") } func main() { var x Animal x = Cat{name: "Flower Flower"} () () }
6. Details of the use of Golang hollow interface and type assertions
Use an empty interface to define a map type data, which is a slice or structure in the data. It gets the value of the corresponding slice content through the index. If an error occurs, the corresponding data must be obtained through the form of type assertion. The same is true for the structure. The case is as follows:
package main import "fmt" type Address struct { Name string Phone int } // Details of the use of Golang hollow interface and type assertionsfunc main() { var userinfo = make(map[string]interface{}) userinfo["username"] = "Zhang San" userinfo["age"] = 20 userinfo["hobby"] = []string{"sleep", "Have a meal"} (userinfo["age"]) (userinfo["hobby"]) // (userinfo["hobby"][1]) //interface {} does not support indexing var address = Address{ Name: "Li Si", Phone: 1521242141, } () //Li Si userinfo["address"] = address (userinfo["address"]) //{Li Si 1521242141} // var name = userinfo["address"].Name //type interface {} is interface with no methods // (name) hobby2, _ := userinfo["hobby"].([]string) (hobby2[1]) //Have a meal address2, _ := userinfo["address"].(Address) (, ) //Li Si 1521242141 }
This is the article about the use of empty interfaces in golang. For more related content on using empty interfaces in golang, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!