Interface Definition:
Use the keyword interface to define an interface, which is a set of methods.
For example:
Interface { string, age intint, err Error) (string, age int)}
Implementation of the interface:
Is the same as the Member method implementation of the struct.
Func (object of implement Func) Func_name (Parameters) (return type) {
....//func body
}
For example:
Package Mainimport"FMT"Func Main () {FMT. Println ("=================live interface===============") varLive Live S:= &student{people{"Puyangsky", A,007},0} Live=s Live.speak ("I am Happy") live.eat () fmt. Println ("================earn interface================") varearn earn Earn= &worker{people{"humeiling", A,002},0} earn.eat () earn.work () Earn.getmoney ( -) fmt. Println ("=====================end======================")}type Peoplestruct{NamestringAge Int32 ID int32}type Studentstruct{people grade Float32}type Workerstruct{People salary Float32}type LiveInterface{eat () speak (somethingstring)}type EarnInterface{eat () work () Getmoney (Money Int32)}func (S*Student) Eat () {FMT. Printf ("%s is eating...\n", S.name)} Func (S*student) Speak (somethingstring) {fmt. Printf ("%s is speaking:%s\n", S.name, something)} Func (W*Worker) Eat () {FMT. Printf ("%s is eating ... \ n", W.name)} Func (W*Worker) Work () {FMT. Printf ("%s is working...\n", W.name)} Func (W*Worker) Getmoney (Money Int32) {fmt. Printf ("%s earned%d money: \ n", W.name, Money)}
The results are as follows:
Use of the interface:
A struct must implement all the methods of an interface in order to be accepted by an interface object. This is the same as the requirements for interfaces in the Java language.
For example, the live interface object in the example above live, can only accept objects that implement the student structure of all methods of the live interface, and cannot accept objects from other structs.
An interface can be implemented by multiple structures, and a struct can implement multiple interfaces, which is a many-to-many relationship.
How to use: First define an object of an interface, initialize the interface object with an object that implements the structure of all the methods of the interface, and then access the interface's methods through the interface object.
interface of "Go" basic syntax