Golang Interface Interface Comprehensive understanding (ii)

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

Now your life, life on the future to play your, now does not work hard, the future suck.

Now do not work hard, future life play you, now do not try, the future does not give strength.

Pointer vs value type implements interface

All of the sample interfaces we discussed in part 1th are implemented using the value receivers. You can also use pointer receivers to implement an interface. The nuances that you need to be aware of when using pointer receivers to implement an interface. Let us know using the following program.

package mainimport "fmt"type Describer interface {Describe()}type Person struct {name stringage  int}func (p Person) Describe() { //implemented using value receiverfmt.Printf("%s is %d years old\n", p.name, p.age)}type Address struct {state   stringcountry string}func (a *Address) Describe() { //implemented using pointer receiverfmt.Printf("State %s Country %s", a.state, a.country)}func main() {var d1 Describer // 接口类型变量p1 := Person{"Sam", 25}d1 = p1  // 值类型d1.Describe()p2 := Person{"James", 32}d1 = &p2  // 指针类型d1.Describe()var d2 Describera := Address{"Washington", "USA"}//d2 = a  // 不能使用值类型(引发panic)①d2 = &a d2.Describe()    a.Describe()  // 直接使用值类型调用②}

Why the above D2 = A panic is raised:

.\interface1.go:39:5: cannot use a (type Address) as type Describer in assignment:Address does not implement Describer (Describe method has pointer receiver)

and A. Describe () does not trigger panic???

The reason is that any pointer variable or variable call pointer method that can get pointers is legal. But the value stored in the interface is not addressable, so the compiler cannot automatically get the pointer address to raise panic.

Or: D2 = A This line error, in short, is passed (Assignment) the object must implement the interface requirements of the method, a does not implement the describe () method, a pointer to implement the describe () method.

Implementing multiple interfaces

A type can implement multiple interfaces. Let's see how this is done in the program below.

package mainimport ("fmt")type SalaryCalculator interface {DisplaySalary()}type LeaveCalculator interface {CalculateLeavesLeft() int}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 s SalaryCalculator = es.DisplaySalary()var l LeaveCalculator = efmt.Println("\nLeaves left =", l.CalculateLeavesLeft())}

Nesting of interfaces

Although go does not provide Java-like inheritance, it is possible to create new interfaces by embedding other interfaces.

Let's see how this is done:

package mainimport ("fmt")type SalaryCalculator interface {DisplaySalary()}type LeaveCalculator interface {CalculateLeavesLeft() 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())//当然更是实现了两个子接口var lc SalaryCalculator = elc.DisplaySalary()}

Interface 0 Value

The 0 value of an interface is nil and has its nil type.

package mainimport "fmt"type Describer interface {      Describe()}func main() {      var d1 Describer    if d1 == nil {        fmt.Printf("d1 is nil and 类型 %T 值%v\n", d1, d1)    }}

If we call a method using the nil interface, the program will panic because nil interface has neither the underlying value nor the corresponding concrete type. Or a null pointer exception like Java!

The end!

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.