Golang API-Oriented Programming-interface (interface)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Golang API-Oriented Programming-interface (interface)

Author: Yun Zhengjie

Copyright Notice: Original works, declined reprint! Otherwise, the legal liability will be investigated.

 

Golang is not a typical language for object-oriented programming (object Oriented Programming,oop, OO programming). It does not support the concept of classes and inheritance in syntax. Is it impossible to have polymorphic behavior without inheritance? The answer is no, we know that there is no concept of class in Golang, but rather that the "duck types" that are common in dynamic type languages are supported by interface type conversions to achieve runtime polymorphism.

I. What is interface

Simply put, interface is a group of method combinations, and we define a set of behaviors for an object by interface. In other words, a interface type defines a "method set" as its interface. A variable of type interface can hold a value of any type that belongs to this interface type, when we say that this type implements this interface. The 0 value of the uninitialized interface type variable is null (nil).

Two. Interface type and value

An interface type is actually a list of method signatures. The interface type defines a set of methods that implement this interface if an object implements all the methods of an interface. An interface is also a data type. If you declare an interface variable, this variable can store any object type that implements the interface. Finally, any type implements the Null interface (we define this: interface{}), which is the interface with 0 method. So I like to give it a nickname called "Big Stomach King".

Define a interface and invoke the following method:

1/*2 #!/usr/bin/env Gorun3 @author: Yinzhengjie4blog:http://www.cnblogs.com/yinzhengjie/tag/go%e8%af%ad%e8%a8%80%e7%9a%84%e8%bf%9b%e9%98%b6%e4%b9%8b%e8%b7%af/5 email:y1053419035@qq.com6*/7 8 Package Main9 Ten Import ( One     "FMT" A     "Strings" - ) -  the type Human struct { -Name string//Define name -string//built-in anonymous fields, which we use to define home addresses.  -Phone int//Phone number + } -  + type Student struct { AHuman//an anonymous field whose type is the type that we have customized above.  atClassroom string//Classroom Name -Score Float64//Exam Results - } -  - type Teacher struct { -Human//Anonymous Fields inPosition string//Job Information -Salary Float64//Salary Status to } +  -  theFunc (H Human) Sayhi () {//defines the method by which the structure "Human" introduces itself.  *Fmt. Printf ("Hello, my name is '%s '. My phone number is "%d". My home address is '%s ' \ n", H.name, $h.phone,h.string)//formatted output is possible to wrap the yo. Panax Notoginseng } -  the  +Func (H Human) Sing (Name string) {//define the method of "Human" singing of structure body AFmt. Printf ("'%s ': I have a little donkey I never ride, one day I ride it to the market on impulse ... \ n", Name) the } +  -  $Func (t Teacher) Sayhi () {//defines the method by which the structure "Teacher" introduces itself.  $Fmt. Printf ("anyway, I ' m your "%s" teacher, you can call me "%s", My salary is ... "%f" \ n", T.position, - t.human.name,t.salary) - } the  - WuyiType Superman interface {//define an interface theSayhi ()//This interface contains the "Sayhi ()" method.  -Sing (Name string)//The interface also contains the "Sing (Name String)" method.  Wu } -  About Func Main () { $YZJ: = student{human{"Yun Zhengjie","Beijing", 7474741},"class One, Grade three .", 95}//initializes the struct we define. We can also call this process an instantiation. and the "Yzj" is called an instance.  -Hsy: = student{human{"Hansen Rain","Beijing", 2424241},"class Five, Grade One .", 100} -Bingan: = teacher{human{"Biscuits","Beijing", 6464641},"Golang", 30000} -  A  +var Yinzhengjie superman//declares a variable whose type is the interface that we define.  the  -Yinzhengjie = YZJ//Note that this is the first type of acceptance of our definition.  $Yinzhengjie. Sayhi ()//and can call the "Sayhi ()" method under this type already "Sing ("Treble singing") "method.  theYinzhengjie. Sing ("Treble singing") the  the  theFmt. Println ("\ n", strings. Repeat ("*", 30),"I'm a split line .", strings. Repeat ("*", 30),"\ n") -  inYin: = make ([]superman,3)//dealing with the most common gameplay above, of course, can also be defined as slices by the Make method.  theYin[0], yin[1], yin[2] = Hsy, Bingan, YZJ//use subscripts to differentiate between different strengths. This time we can find that the Superman type can accept "Student" and "Teacher" type of data, although this is two different structures, but can still be called through an interface, so I call it "big stomach king."  the  About      for_, Value: = Range yin{//then we can call 3 methods at the same time!  the value. Sayhi () the     } the } +  -  the Bayi #The result of the above code execution is as follows: theHello, my Name is"Yun Zhengjie". My Phone Number is"7474741". My Home Address is"Beijing" the "Treble singing": I have a small donkey I never ride, one day I ride it on a whim to the market .... -  -I'm the split line ******************************. the  theHello, my Name is"Hansen Rain". My Phone Number is"2424241". My Home Address is"Beijing" theAnyway, I'm your "Golang" teacher, you can call me "cookie", My salary is ... "30000.000000" theHello, my Name is"Yun Zhengjie". My Phone Number is"7474741". My Home Address isBeijing

by the above code we can know that interface can be implemented by arbitrary objects. Similarly, an object can implement any number of interface. You will find that interface is a collection of abstract methods that must be implemented by other non-interface types and not self-fulfilling , and go through interface implements Duck-typing: " When you see a bird walking like a duck, swimming like a duck, and barking like a duck, the bird can be called a duck.

Three. Empty interface

empty Interface (interface{}) does not contain any method, and because of this, all types implement an empty interface. The null interface does not have any effect on the description (because it does not contain any method), but the null interface is useful when we need to store any type of numeric value, because it can store any type of value. a function takes interface{} as a parameter, then he can accept any type of value as a parameter, and if a function returns interface{}, it can return any type of value. is not an instant feel interface is very magical!

1/*2 #!/usr/bin/env Gorun3 @author: Yinzhengjie4blog:http://www.cnblogs.com/yinzhengjie/tag/go%e8%af%ad%e8%a8%80%e7%9a%84%e8%bf%9b%e9%98%b6%e4%b9%8b%e8%b7%af/5 email:y1053419035@qq.com6*/7 8 Package Main9 Ten Import ( One     "FMT" A     "reflect" - ) -  the func Myecho () { -Fmt. Println ("I have a small donkey I never ride, one day I ride it on the whim of the market .....") - } -  + Func Main () { -Name: ="Yun Zhengjie"//I have defined three different types here, namely, String, Integer, number of bytes, and so on.  +Age: = 18 ALanguage: = []byte ("Golang") at FMT. Println (reflect. TypeOf (Name), reflect. TypeOf (age), reflect. TypeOf (Language)) -var Yinzhengjie interface{}//defines an empty interface, because each data type implements an empty interface. So we use this feature to accept any type of data.  -Yinzhengjie =Name -Fmt. Printf ("the value of the variable is: \033[31;1m "%v" \033[0m, whose type is: \033[31;1m "%v" \033[0m\n", Yinzhengjie,reflect. TypeOf (Yinzhengjie)) -Yinzhengjie = Age -Fmt. Printf ("the value of the variable is: \033[31;1m "%v" \033[0m, whose type is: \033[31;1m "%v" \033[0m\n", Yinzhengjie,reflect. TypeOf (Yinzhengjie)) inYinzhengjie =Language -Fmt. Printf ("the value of the variable is: \033[31;1m "%v" \033[0m, whose type is: \033[31;1m "%v" \033[0m\n", Yinzhengjie,reflect. TypeOf (Yinzhengjie)) to } +  -  the  * #The result of the above code execution is as follows: $ string int []uint8Panax Notoginseng The value of the variable is: "Yun Zhengjie", whose type is: "String" -The value of the variable is: "18", whose type is:" int " theThe value of the variable is: "[71 111 108 97 110 103]", whose type is: "[]uint8"

Four. Interface function parameters

The interface variable can hold any object that implements the interface type, which gives us some extra thought about how to write the function (including method), whether we can define the interface parameter and let the function accept the arguments of each type. as an example: FMT. PRINTLN is a common function of ours, but do you notice that it can accept any type of data? Open the FMT source file and you will see a definition like this:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.