Go Series Tutorial--19. Interface (ii)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. Welcome to the 19th Tutorial [Golang Series Tutorial] (/SUBJECT/2). Interface There are two tutorials, this is our second tutorial. If you have not read the previous tutorial, please read [Interface (i)] (https://studygolang.com/articles/12266). # # # Implementation interface: The pointer receiver and the value recipient in all examples on [Interface (i)] (https://studygolang.com/articles/12266), we use value receiver to implement the interface. We can also implement the interface using the pointer recipient (Pointer Receiver). But there are some details to be aware of when implementing an interface with a pointer recipient. Let's use the code below to understand it. ' Gopackage mainimport ' FMT ' type Describer interface {Describe ()}type person struct {name stringage int}func (P person) Describe () {//uses the value recipient to implement FMT. Printf ("%s is%d years old\n", P.name, p.age)}type Address struct {State stringcountry string}func (a *address) Describe () {//Use the pointer recipient to implement FMT. Printf ("State%s country%s", A.state, A.country)}func main () {var D1 Describerp1: = person{"Sam", 25}d1 = p1d1. Describe () P2: = person{"James", 32}d1 = &p2d1. Describe () var d2 describera: = address{"Washington", "USA"}/* if the following line uncomment causes a compilation error: cannot use a (type Address) as type DESCR Iber in assignment:address does no implement Describer (Describe method has pointer Receiver) *///d2 = Ad2 = &a//This is legal//because in line 22nd, the Address type pointer implements the Describer interface D2. Describe ()} "[Online Run Program] (https://play.golang.org/p/IzspYiAQ82) in the above program in line 13th, the struct ' person ' uses the value of the recipient, the implementation of the ' Describer ' interface. We have already mentioned in our discussion of [method] (https://studygolang.com/articles/12264) that using a method declared by a value recipient can be invoked either by a value or by a pointer. * * Whether it is a value or a pointer that can be dereferenced, calling such a method is legal * *. The ' P1 ' type is ' person ', and in line 29th, ' P1 ' assigns a value to ' D1 '. Because ' person ' implements the interface variable ' D1 ', in line 30th, it prints ' Sam is years old '. Next on line 32nd, ' D1 ' is also assigned to ' &AMP;P2 ', and on line 33rd the same printout of ' James is years '. Nice and clean. :) In line 22, the struct ' Address ' implements the ' Describer ' interface using the pointer recipient. In the above program, if you remove the comment from line 45th, we get a compile error: ' Main.go:42:cannot use a (type Address) as type describer in assignment:address does not Implement Describer (Describe method has pointer receiver) '. This is because in line 22nd, we implemented the interface ' describer ' using the ' Address ' type of the pointer recipient, and then we tried to use ' a ' to assign the value ' D2 '. However, ' a ' is a value type and it does not implement the ' Describer ' interface. You should be surprised, because we have learned that using the pointer recipient's [method] (https://studygolang.com/articles/12264), both pointer and value can call it. So why doesn't the code in line 45th work? The reason for this is that for a method that uses a pointer recipient, it is legitimate to call with a pointer or a value that can get an address. But in the mouthThe stored specific value (concrete value) does not fetch the address, so in line 45th, the compiler cannot automatically get the address of ' a ', so the program error * *. The 47th line will run successfully because we assign the ' a ' address ' &a ' to ' D2 '. Other parts of the program are self-evident. The program will print: ' Sam is years old James was years old state Washington country USA ' # # # implements multiple interface types to implement multiple interfaces. Let's see how the following procedure is done. "' Gopackage mainimport (" FMT ") type Salarycalculator interface {displaysalary ()}type Leavecalculator interface {Calcul Ateleavesleft () int}type Employee struct {firstName stringlastname stringbasicpay INTPF inttotalleaves Intleavestaken in T}func (e Employee) displaysalary () {fmt. Printf ("%s%s has salary $%d", E.firstname, E.lastname, (E.basicpay + e.pf))}func (e Employee) calculateleavesleft () int { return E.totalleaves-e.leavestaken}func Main () {e: = Employee {firstName: "Naveen", LastName: "Ramanathan", basicpay:50 00,pf:200,totalleaves:30,leavestaken:5,}var s salarycalculator = es. Displaysalary () var l leavecalculator = efmt. Println ("\nleaves left =", L.calculateleavesleft ())} "[Running Program Online] (Https://play.golang.org/p/DJxS5zxBcV)Two interfaces were declared on lines 7th and 11th: ' Salarycalculator ' and ' leavecalculator '. The 15th line defines the struct ' Employee ', which implements the ' displaysalary ' method of the ' Salarycalculator ' interface on line 24th, and then implements the ' Leavecalculator ' interface in the 28th line ' Calcul Ateleavesleft ' method. So ' Employee ' realized the ' salarycalculator ' and ' Leavecalculator ' two interfaces. Line 41st, we assign the ' E ' to the ' Salarycalculator ' type of interface variable, and in 43 rows, we also assign ' E ' to the ' leavecalculator ' type of the interface variable. Because the type ' Employee ' of ' e ' implements the ' Salarycalculator ' and ' Leavecalculator ' two interfaces, this is legal. The program outputs: "' Naveen Ramanathan has salary $5200 Leaves left = 25" # # # interface Nested Although the Go language does not provide an inheritance mechanism, you can create a new interface by nesting other interfaces. Let's see how this can be achieved. "' Gopackage mainimport (" FMT ") type Salarycalculator interface {displaysalary ()}type Leavecalculator interface {Calcul Ateleavesleft () Int}type employeeoperations interface {salarycalculatorleavecalculator}type Employee struct { FirstName stringlastname stringbasicpay INTPF inttotalleaves intleavestaken int}func (e Employee) displaysalary () {fmt. Printf ("%s%s has salary $%d", E.firstname, E.lastname, (E.basicpay + e.pf))}fuNC (e Employee) calculateleavesleft () int {return E.totalleaves-e.leavestaken}func main () {e: = Employee {firstName: " Naveen ", LastName:" Ramanathan ", basicpay:5000,pf:200,totalleaves:30,leavestaken:5,}var empop employeeoperations = Eempop.displaysalary () fmt. Println ("\nleaves left =", Empop.calculateleavesleft ())} "[Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/HIA7D-WBZP) in the above program 15 lines, we created a new interface ' Employeeoperations ', which nested two interfaces: ' Salarycalculator ' and ' leavecalculator '. If a type defines the methods contained in the ' Salarycalculator ' and ' leavecalculator ' interfaces, we call the type to implement the ' Employeeoperations ' interface. In lines 29th and 33rd, because the ' Employee ' struct defines the ' displaysalary ' and ' calculateleavesleft ' methods, it implements the interface ' Employeeoperations '. In line 46, the ' Empop ' type is ' employeeoperations ', the ' e ' type is ' Employee ', we assign ' Empop ' to ' e '. The next two lines, ' Empop ' Call the ' displaysalary () ' and ' Calculateleavesleft () ' methods. The program output: "' Naveen Ramanathan has salary $5200leaves left = 25" # # # Interface 0 Value interface 0 value is ' nil '. For an interface with a value of ' nil ', the underlying value (underlying value) and the concrete type (concrete type) are ' nil '. "' Gopackage mainimport" FMT "type DesCriber interface {Describe ()}func main () {var D1 describerif D1 = = Nil {fmt. Printf ("D1 is nil and have type%T value%v\n", D1, D1)} "[Online Run Program] (Https://play.golang.org/p/vwYHC6Y78H) The above program ' D1 ' equals ' Nil ', the program outputs: ' ' D1 is nil and have type <nil> value <nil> ' for an interface with value ' nil ', because there is no underlying value and specific type, when we try to invoke its method, the program generates ' Pani C ' exception. "' Gopackage MainType describer interface {Describe ()}func main () {var D1 describerd1.describe ()}" [Run Program online] (https:// Play.golang.org/p/rm-ry0ugti) in the above program, ' D1 ' equals ' nil ', the program generates run-time error ' panic ': * * ' panic:runtime error:invalid memory address or N Il pointer dereference [signal sigsegv:segmentation violation code=0xffffffff addr=0x0 pc=0xc8527] ' * *. This concludes the introduction of the interface. Have a nice day. * * Previous tutorial-[interface-I] (https://studygolang.com/articles/12266) * * * Next tutorial-[concurrency] (https://studygolang.com/articles/12341) * *

via:https://golangbot.com/interfaces-part-2/

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

2,510 Reads

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.