Golang Interface understanding again

Disclaimer: This article is a blogger original article, reprinted need to add a description link. https://blog.csdn.net/makenothing/article/details/88080726

Interface

Golang in interface to understand, we must first clear some common sense:

  1. interface may represent a type (any type)
  2. interface is a set of methods (i.e. methods set of interfaces)
  3. As long as the interface to achieve all the way, then you would think that implements this interface (called Duck typing)

Duck typing: is a form of polymorphism (polymorphism) in such form, regardless of what the object belongs, regardless of the specific interfaces are declared, as long as the object implements the corresponding method, function, operation can be performed on the object. That is true regardless of the type of the object, and focus instead on object has no method to achieve the required signatures and semantics.

'If it walks like a duck to start, and sounds like a duck, that it must be a duck.'

interface is a collection of a set of abstract methods that must be implemented by other types of non-interface, and can not self-fulfilling;
interface may be implemented as any object, a type / object can also be achieved plurality of interface
methods can not be overloaded, as EAT (), eat (s string) can not coexist
Example:

package main

import "fmt"

type Phone interface {
    call()
}

type NokiaPhone struct {
}

func (nokiaPhone NokiaPhone) call() {
    fmt.Println("I am Nokia, I can call you!")
}

type ApplePhone struct {
}

func (iPhone ApplePhone) call() {
    fmt.Println("I am Apple Phone, I can call you!")
}

func main() {
    var phone Phone
    phone = new(NokiaPhone)
    phone.call()

    phone = new(ApplePhone)
    phone.call()
}

If the interface A implements the interface B, all of the methods, then A can be converted to B interface.
After using the struct to implement the interface, we can use this as a struct interface parameters, interface parameters to use those methods to receive our complete functionality. This is also the interface for programming the way we function based interface to implement, without concern for what is implementation of the interface is so much versatility provides scalable functionality.

func PhoneCall(phone Phone) {
		phone.call()
}

func main() {
		var ph1 Phone
		iphone := &iPhone
		ph1 = iphone
		
		PhoneCall(ph1 )
}

Guess you like

Origin blog.csdn.net/makenothing/article/details/88080726