This is a creation in Article, where the information may have evolved or changed. Welcome to the 18th Tutorial [Golang Series Tutorial] (/SUBJECT/2). There are two tutorials in the interface, which is the first tutorial for our interface. # # # What is an interface? In the field of object-oriented, the interface is generally defined as: * * The interface defines the behavior of an object * *. The interface only specifies what the object should do, and how to implement the behavior (i.e. implementation details) is determined by the object itself. In the Go language, an interface is a collection of method signatures (methods Signature). When a type defines all the methods in an interface, we say that it implements the interface. This is similar to the idea of object-oriented programming (OOP). The * * Interface Specifies the method that a type should have, and the type determines how these methods are implemented * *. For example, ' Washingmachine ' is an interface containing the ' cleaning () ' and ' drying () ' two methods. Any type that defines the ' cleaning () ' and ' drying () ' is said to implement the ' Washingmachine ' interface. The Declaration and implementation of the # # # interface Let's write the code, create an interface and implement it. "' Gopackage mainimport (" FMT ")//interface DefinitionType Vowelsfinder Interface {findvowels () []rune}type MyString str Ing//mystring implements Vowelsfinderfunc (MS MyString) Findvowels () []rune {var vowels []rune for _, Rune: = Range ms { If Rune = = ' A ' | | Rune = = ' E ' | | Rune = = ' I ' | | Rune = = ' O ' | | Rune = = ' U ' {vowels = append (vowels, rune)}} return Vowels}func main () {name: = MyString ("Sam Anderson") Var v vowelsf Inder v = name//possible since MyString implements Vowelsfinder FMT. Printf ("Vowels is%c", V.findvowels ())} "[Online Running program] (Https://play.golang.org/p/F-T3S_wNNB) on line 8th of the above program, create an interface named ' Vowelsfinder ', which has a ' findvowels () []rune ' method. In the next line, we created a ' MyString ' type. * * In line 15th, we added the method ' Findvowels () []rune ') to the receiver type ' MyString '. Now, we say ' MyString ' implements the ' Vowelsfinder ' interface. This is very different from other languages such as Java, and some other languages require that a class use the ' implement ' keyword to explicitly declare that the class implements the interface. In Go, this is not required. If a type contains all the methods declared in the interface, it implicitly implements the Go interface * *. In line 28th, ' V ' is of type ' vowelsfinder ', ' name ' is of type ' MyString ', we assign ' name ' to ' V '. Because ' MyString ' implements ' Vowelfinder ', this is legal. On the next line, ' V.findvowels () ' calls the ' MyString ' type ' findvowels ' method to print the string ' Sam Anderson ' all the vowels. The program outputs ' vowels is [a e O] '. Congratulate! You have created and implemented your first interface. # # # Interface The actual use of the previous example teaches us to create and implement the interface, but has not yet told us the actual use of the interface. In the above program, if we use ' name '. Findvowels () ', not ' v.findvowels ', the program can still run as usual, but the interface does not reflect the actual value. So, let's talk about the actual application scenario for the interface. We write a simple program that calculates the total expenses of the company based on the individual salary of the company's employees. For simplicity's sake, we assume that the units of expenditure are in dollars. "' Gopackage mainimport (" FMT ") type Salarycalculator interface {calculatesalary () Int}type Permanent struct {empId int Basicpay int PF int}type contract struct {empId int Basicpay Int}//salary of permanent employee is sum of basic pay and Pffunc (P permanent) calculatesalary () int {RE Turn P.basicpay + p.pf}//salary of contract employee is the basic pay Alonefunc (c contract) calculatesalary () int {retur n c.basicpay}/*total expense is calculated by iterating though the Salarycalculator slice and summing the salaries of the Individual employees */func Totalexpense (s []salarycalculator) {expense: = 0 for _, V: = range s {expense = expense + v. Calculatesalary ()} FMT. Printf ("Total Expense Per Month $%d", Expense)}func main () {pemp1: = Permanent{1,, pemp2: = permanent{2, 6000, 3 0} CEMP1: = contract{3, +/-Employees: = []salarycalculator{pemp1, PEMP2, CEMP1} totalexpense (Employees)} ' [Run Program online] ( Https://play.golang.org/p/5t6GgQ2TSU) The 7th line of the above program declares a ' Salarycalculator ' interface type, which has only one method ' calculatesalary () int '. In the company, we have two categories of employees, the structure defined by lines 11th and 17th: ' Permanent ' and ' contract '. Long-term employees (' Permanent ') are paid in combination with ' basicpay ' and ' PF ', while contract staff (' contract ') have a base salary of only ' BASICPAY '. In lines 23rd and 28th, the method ' Calculatesalary ' respectively implements the above relationship. Because both ' Permanent ' and ' contract ' declare the method, they all implement the ' Salarycalculator ' interface. The ' Totalexpense ' method declared in line 36th embodies the magical usage of the interface. The method receives a slice of the ' Salarycalculator ' interface (' []salarycalculator ') as a parameter. In line 49th, we pass a slice containing ' Permanent ' and ' contact ' types to the ' Totalexpense ' method. In line 39th, by invoking the ' Calculatesalary ' method corresponding to the different types, ' totalexpense ' can calculate the payout. The biggest advantage of this is that ' totalexpense ' can extend the new employee type without needing to modify any code. If the company adds a new type of employee ' Freelancer ', it has a different salary structure. ' Freelancer ' only needs to be passed to the ' totalexpense ' slice parameter without modifying the ' totalexpense ' method itself. As long as ' Freelancer ' also implements the ' Salarycalculator ' interface, ' Totalexpense ' is able to implement its function. The program outputs ' total Expense Per Month $14050 '. The inside of the # # # interface means that we can think of an interface as an internal tuple ' (type, value) '. ' Type ' is the concrete type (concrete type) at the bottom of the interface, and ' value ' is the value of the specific type. We write a program to better understand it. "' Gopackage mainimport (" FMT ") type Test interface {Tester ()}type myfloat Float64func (M myfloat) Tester () {fmt. Println (m)}func describe (t Test) {FMT. Printf ("Interface type%T value%v\n", T, T)}func Main () {var t Test f: = Myfloat (89.7) T = f describe (t) t.tester ()} "[The online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/Q40OMTEWLH) ' Test ' interface has only one method ' Tester () ', and the ' myfloat ' type implements the interface. In line 24th, we assign the variable ' F ' (' myfloat ' type) to ' t ' (the ' Test ' type). Now the concrete type of ' t ' is ' myfloat ', and the value of ' t ' is ' 89.7 '. The ' describe ' function on line 17th prints out the specific type and value of the interface. The program outputs: ' ' Interface type main. Myfloat value 89.7 89.7 "# # # NULL interface There is no interface that contains methods called NULL interfaces. The empty interface is represented as ' interface{} '. Because the null interface has no methods, all types implement an empty interface. "' Gopackage mainimport (" FMT ") func describe (i interface{}) {FMT. Printf ("Type =%T, value =%v\n", I, I)}func main () {s: = "Hello World" describe (s) I: = describe (i) strt: = struct { Name string} {name: "Naveen R",} describe (STRT)} "[Running Program Online] (HTTPS://PLAY.GOLANG.ORG/P/FM5KESCOJB) on line 7th of the above program, ' The describe (i interface{}) ' function receives an empty interface as a parameter, so you can pass any type to the function. In lines 13th, 15th and 21st, we pass the ' string ', ' int ', and ' struct ' to the ' describe ' function, respectively. The program prints: ' type = string, value = Hello World type = int, value = $ = Type = struct {name string}, value = {Naveen R} ' # The # # Type assertion type assertion is used to extract the underlying value of the interface (underlying value). In syntax ' I (t) ', the concrete type of interface ' I ' is ' T ', which is used to get the underlying value of the interface. A piece of code trumps thousands of words. Write down aTo the type assertion program. "' Gopackage mainimport (" FMT ") func assert (I interface{}) {s: = i. (int)//get the underlying int value from I fmt. Println (s)}func main () {var s interface{} = assert (s)} ' [Online Run Program] (Https://play.golang.org/p/YstKXEeSBL) on line 12th, ' s ' with The body type is ' int '. In line 8th, we use the syntax ' I (int) ' to extract the underlying int value of ' I '. The program will print ' 56 '. In the above program, what happens if the specific type is not int? Next look. "' Gopackage mainimport (" FMT ") func assert (I interface{}) {s: = I. (int) FMT. Println (s)}func main () {var s interface{} = "Steven Paul" assert (s)} "[Running Program Online] (Https://play.golang.org/p/88KflSceHK) In the above program, we passed the specific type ' string ' ' s ' to the ' assert ' function, attempting to extract an int value from it. The program will error: ' Panic:interface conversion:interface {} is a string, not int. '. To resolve this problem, we can use the following syntax: ' gov, ok: = i. (t) ' ' If the specific type of ' I ' is ' T ', then ' V ' is assigned the underlying value of ' I ', and ' OK ' is assigned ' true '. If the specific type of ' I ' is not ' t ', then the ' OK ' assignment is ' false ' and ' V ' is assigned a value of ' t ' type of 0, * * The program will not error * * at this time. "' Gopackage mainimport (" FMT ") func assert (I interface{}) {V, OK: = i (int) fmt. Println (V, OK)}func main () {var s interface{} = $ assert (s) var iinterface{} = "Steven Paul" assert (i)} "[Running Program Online] (Https://play.golang.org/p/0sB-KlVw8A) When passing ' Steven Paul ' to ' assert ' function , because the specific type of ' I ' is not ' int ', ' OK ' is assigned ' false ' and ' V ' is assigned a value of 0 (int 0 value). The program prints: ' ' 0 false ' ' # # # type selection (type Switch) type selection is used to compare the specific type of the interface with the type specified by many case statements. It is similar to a general switch statement. The only difference is that the type selection specifies the type, and the general switch specifies the value. The syntax for type selection is similar to a type assertion. The syntax for type assertion is ' I. (t) ', and for type selection, the type ' T ' is replaced by the keyword ' type '. Let's see how the program works. ' Gopackage mainimport ("FMT") func Findtype (i interface{}) {switch I. (type) {case string:fmt. Printf ("I am a string and my value is%s\n", I. (string)) case int:fmt. Printf ("I am an int. and my value is%d\n", I. (int)) default:fmt. Printf ("Unknown type\n")}}func Main () {Findtype ("Naveen") Findtype () Findtype (89.98)} "[Running program online] (https:// Play.golang.org/p/xypdwovoch) in line 8th of the above procedure, ' switch I (type) ' represents a type selection. Each case statement compares the specific type of ' I ' with a specified type. If the case matches successfully, the corresponding statement is printed out. The program outputs: ' I am a string and my value is Naveen I am an int and my value is Unknown the type ' 89.98 ' in line 20th ' float 64 ', noThere was a successful match on case, so the last line printed ' Unknown type '. * * You can also compare a type and an interface. If a type implements an interface, the type and the interface it implements can be compared to each other. To illustrate this point, write a program below. ' Gopackage mainimport ' FMT ' type Describer interface {Describe ()}type person struct {name string age Int}func (p person ) Describe () {fmt. Printf ("%s is%d years old", P.name, P.age)}func findtype (i interface{}) {Switch V: = I. (type) {case DESCRIBER:V.DESCRI Be () default:fmt. Printf ("Unknown type\n")}}func Main () {Findtype ("Naveen") P: = person{name: "Naveen R", Age:25,} "Findtype (P)}" [Run online Program] (Https://play.golang.org/p/o6aHzIz4wC) in the above program, the struct ' person ' implements the ' Describer ' interface. In the case statement in line 19th, the ' V ' is compared to the interface type ' Describer '. ' P ' implements ' describer ' and therefore satisfies the case statement, so the program calls the ' Describe () ' method when the program runs to ' Findtype (p) ' on line 32nd. The program outputs: "' Unknown type Naveen R is years the contents of the ' interface (a) to this end. In the interface (ii) we will continue to discuss the interface. I wish you a happy! * * Previous Tutorial-[method] (https://studygolang.com/articles/12264) * * * * Next tutorial-[interface-II] (https://studygolang.com/articles/12325) * *
via:https://golangbot.com/interfaces-part-1/
Author: Nick Coghlan Translator: Noluye proofreading: polaris1119
This article by GCTT original compilation, go language Chinese network honor launches
This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove
3,874 Reads