1

interface

Suppose I have a HUAWEI class, to implement the Phone interface, I can do this:

 package main

import "fmt"

//定义一个接口
type Phone interface {
    call()
}

//定义一个类
type HUAWEI struct {
    name string
}

//用上面的HUAWEI类实现上面的Phone接口
func (myPhone HUAWEI) call() {
    fmt.Println("this is the coolest phone all around the world")
}

func main() {
    thisPhone := new(HUAWEI)
    thisPhone.call()
}

polymorphism

Go's polymorphism can be implemented with interfaces. The so-called polymorphism is the different performance of different objects under the same interface.
For example, if we want to use polymorphism to implement the purchase of a MacBook and an Apple Watch, we can write:

  1. Define the interface of the product
  2. Define two classes, laptop and watch
  3. Each of the above classes implements the commodity interface (in fact, the so-called implementation interface is the method of binding all interface declarations)
  4. Create a slice of the merchandise to represent the shopping cart
  5. Define a function to calculate the total amount The specific implementation code of the function is as follows
 package main

import (
    "fmt"
    "strconv"
)

//定义一个接口来表示商品

type Merchandise interface {
    totalPrice() int
    totalInfo() string
}

//定义两个类 :Laptop 和 Watch
type Laptop struct {
    brand    string
    quantity int
    price    int
}

type Watch struct {
    brand    string
    quantity int
    price    int
}

//上面的每一个类都实现一下Merchandise接口(其实所谓的实现接口 就是绑定所有接口声明的方法)
func (laptop Laptop) totalPrice() int {
    return laptop.price * laptop.quantity
}
func (laptop Laptop) totalInfo() string {
    return `your order contains ` + strconv.Itoa(laptop.quantity) + ` ` + laptop.brand + ` total: ` + strconv.Itoa(laptop.totalPrice()) + ` RMB`
}

func (watch Watch) totalPrice() int {
    return watch.price * watch.quantity
}
func (watch Watch) totalInfo() string {
    return `your order contains ` + strconv.Itoa(watch.quantity) + ` ` + watch.brand + ` total: ` + strconv.Itoa(watch.totalPrice()) + ` RMB`
}

//定义一个函数计算总金额的函数
func calculateTotalPrice(merchandise []Merchandise) int {
    var finalPrice int
    for _, item := range merchandise {
        fmt.Println(item.totalInfo())
        finalPrice += item.totalPrice()
    }
    return finalPrice
}

func main() {
    //    实例化两个类
    macBook := Laptop{
        brand:    "Apple-macbook",
        quantity: 1,
        price:    20000,
    }
    appleWatch := Watch{
        brand:    "AppleWatch",
        quantity: 1,
        price:    5000,
    }
    //    创建一个merchandise的切片来表示购物车
    shoppingCart := []Merchandise{macBook, appleWatch}
    //    计算总价
    finalTotalPrice := calculateTotalPrice(shoppingCart)
    fmt.Println("All you Need to pay is: ", finalTotalPrice, " RMB")
}

Notice

  • In the above main, we did not use var xxx InterfaceName to explicitly implement an interface, but implicitly declare it with :=, so that we will not be able to bind methods other than interfaces to our classes due to interface restrictions. , for details, please refer to https://golang.iswbm.com/c02/c02_06.html
  • Type assertion can be performed only if the static type is an interface, otherwise it needs to be converted to an interface type as follows, for example

     package main
    
    import "fmt"
    
    func main() {
      a := 10
    
      switch interface{}(a).(type) {
      case int:
          fmt.Println("参数的类型是 int")
      case string:
          fmt.Println("参数的类型是 string")
      }
    }

LiberHome
409 声望1.1k 粉丝

有问题 欢迎发邮件 📩 liberhome@163.com