This is a creation in Article, where the information may have evolved or changed.
First, the interface definition
1. Definition
Interface types can define a set of methods, but these do not need to be implemented, and interface cannot contain any variables
Package Mainimport ( "FMT") type test interface{ print ()}type Student struct{ name string age int Score Int}func (P *student) print () { fmt. Println ("name", P.name) FMT. Println ("Age", P.age) FMT. Println ("Score", P.score)}func main () { var t test //Create interface object var stu student=student{ //Instantiate struct body Name: "STU1", age:20, score:100, } t=&stu //Instantiate to this interface object T.print () //Interface object to invoke the interface method}name stu1age 20score 100 The test above is a type
Polymorphic:
A variety of forms of food, can be operated according to a unified interface
The above t can point to Stu, or to other types, this is polymorphic
Defined:
Like what:
Type Example interface{
Method1 (parameter list) return value list
METHOD2 (parameter list) return value list
}
Interface type default is a pointer
Interface implementation:
A, Golang in the interface, do not need to display the implementation, as long as a variable, contains all the methods in the interface type, then this variable to implement this interface
b, if a variable contains multiple interface types of methods, then this variable implements multiple interfaces
C, to implement all the methods of the interface in the variable, is to implement this interface
Interface nesting:
An interface can be nested in another interface, as shown below
Type ReadWrite interface{
Read (b Buffer) bool
Write (b Buffer) bool
}
Type Lock interface{
Lock ()
Unlock ()
}
Type File interface{
ReadWrite
Lock
Close ()
}
Type assertion
Type assertion, because the interface is generic type, do not know the specific type, if you want to turn into a specific type, you can use the following methods to convert
var t int var t int
var x interface{} var x interface {}
X=t x=t
Y=x. (int)//turn int y, ok=x. (int)//turn int, with check
Binary sort Tree
Time complexity and binary search time complexity are the same
Why should I use an interface?
An interface is a specification that requires no attention to the implementation of classes. That is, the data is in MySQL and then suddenly into the PG inside, as long as the interface is not changed, the user does not need to change
If there is no method in the interface, then we call this interface as an empty interface
Package Mainimport ( "FMT") type carer interface{ GetName () string Run () DIDI ()}func main () { var Car carer FMT. Println (car) //<nil> The value of this interface printed above is nil
Use the following specific interfaces:
package main
import (
fmt
)
Type Carer Interface {
GetName () string //The method previously defined here, followed by the return value type
Run ()
DIDI ()
}
type BWM struct {
Name string
}
func (P *bwm) GetName () string{
return p. Name
}
func (P *bwm) Run () {
fmt. Printf ("%s isrunning", p.name)
}
func (P *bwm) DIDI () {
fmt. Printf ("%s Isdidi", p.name)
}
func Main () {
var car carer
FMT. PRINTLN (car) //<nil>
bwm:=bwm{
Name: "BWM",
car=&bwm
car. Run ()
}
Interface Operation Summary:
1, define the interface and method, note the return value
2. Definition type
3, define the type of implementation of the interface method, note that the interface to implement all the methods
4. Declare the type of the definition, declare the type of the interface variable and initialize it, and assign the defined type to the type of the interface variable, note that the pointer
5. Executing interface methods with defined interface variables
Duck type
As long as the interface-related protocols are implemented, this is the interface
If you need to implement the following interface, you can
The Func Sort (data Interface) here only needs to be passed in to the interface.
This interface implements the following methods
Type Interface interface{
Len () int length
Less (I,jint) bool comparison two numbers
Swap (I,jint) Exchange two numbers
}
Note the following case
Package Mainimport ( "FMT", "Math/rand" " Sort") type Student struct{ Name string Id string age Int}type Studentarray []student //Define this is the slice struct func (P studentarray) len () int { return Len (P)}func (P Studentarray ) less (i,j int) bool{ return p[i]. NAME>P[J]. Name //from large to small}func (P studentarray) Swap (i,j int) { P[i],p[j]=p[j],p[i]}func main () { var stus studentarray For I: = 0; i < i++ { stu: = student{ name:fmt. Sprintf ("stu%d", Rand. INTN (+)), Id: fmt. Sprintf ("110%d", Rand. Int ()), age : rand. INTN (+), } stus = Append (Stus, stu) } for _, V: = Range Stus { fmt. Println (v) } //blank line FMT. Println ("\ n") //Because the sort interface is implemented here, you can call sort directly here . Sort (Stus) for _, V: = Range Stus { fmt. Println (v) }}
Reflection
Reflection, which can dynamically get information about a variable at run time
Import ("reflect")
Two functions
a) reflect. TypeOf, gets the type of the variable and returns the reflect. Type types
b) reflect. ValueOf gets the value of that variable, and returns the reflect. Value type
c) reflect. Value.kind gets the category of the variable, returns a variable
d) Reflect.value.Interface () converted to Interface type
The difference between A and C:
Differences in type and category
Category Scope Type
Package Mainimport ("FMT" "reflect") type Student struct{Name string Age int score Float32}func Test (b interface {}) {T:=reflect. TypeOf (b) fmt. Println (t)//main. Student type V:=reflect. ValueOf (b) k:=v.kind () fmt. Println (k)//struct category Iv:=v.interface () Stu,ok:=iv. (Student) if ok{fmt. Printf ("%v%t\n", Stu,stu)//{stu01, Main. Student}}func Main () {var a student=student{Name: "Stu01", Age:18, score:92,} test (a)} can be run at dynamic time A lot of information to B, which is the reflection above is three conversions under Main is to get the value of package Mainimport ("FMT" "reflect") type Student struct{Name string Age int Score Float32}func Test (b interface {}) {T:=reflect. TypeOf (b) fmt. Println (t)//main. Student type V:=reflect. ValueOf (b) k:=v.kind () fmt. Println (k)//struct category Iv:=v.interface () Stu,ok:=iv. (Student) if ok{fmt. Printf ("%v%t\n", Stu,stu)//{stu01, Main. Student}}func testint (b interface{}) {val: =reflect. ValueOf (b) c:=val. Int ()//Get value FMT. Printf ("Get VAlue interface{}%d ", c)//get value interface{} 1234}func main () {var a student=student{Name:" Stu01 ", Age:18, score:92,} test (a) Testint (1234)} Summary: 1, the reflection obtains the concrete type 2, turns into the concrete value 3,. Int () to obtain a specific value of 4, in order to print the output value