golang接口

接口是方法的集合,接口不需要考虑类型的属性是否一致,只需要考虑类型是否实现了接口的方法。

比如接口不需要考虑例二中的类型student和employee的属性,都可以传入接口,只需要他们实现了接口中的方法,并且方法都可以不一样。

package main
import (
    "fmt"
    "math"
    )
type geometry interface {
    area() float64
    perim() float64
}
type rect struct {
    width, height float64
}
type circle struct {
    radius float64
}
func (r rect) area() float64 {
    return r.width * r.height
}
func (r rect) perim() float64 {
    return 2*r.width + 2*r.height
}
func (c circle) area() float64 {
    return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
    return 2 * math.Pi * c.radius
}

func main() {
    r := rect{ 3, height: 4}
    c := circle{radius: 5}
    var g geometry
    //接口可以传入满足接口的类型,只需要类型实现了接口的所有方法
    g = r
    fmt.Println(g)
    fmt.Println(g.area())
    fmt.Println(g.perim())
    g = c
    fmt.Println(g)
    fmt.Println(g.area())
    fmt.Println(g.perim())

}

  

  

接口实例

package main

    import "fmt"

    type Human struct {
        name string
        age int
        phone string
    }

    type Student struct {
        Human //匿名字段
        school string
        loan float32
    }

    type Employee struct {
        Human //匿名字段
        company string
        money float32
    }

    //Human实现SayHi方法
    func (h Human) SayHi() {
        fmt.Printf("Hi, I am %s you can call me on %s
", h.name, h.phone)
    }

    //Human实现Sing方法
    func (h Human) Sing(lyrics string) {
        fmt.Println("La la la la...", lyrics)
    }

    //Employee重载Human的SayHi方法
    func (e Employee) SayHi() {
        fmt.Printf("Hi, I am %s, I work at %s. Call me on %s
", e.name,
            e.company, e.phone)
        }

    // Interface Men被Human,Student和Employee实现
    // 因为这三个类型都实现了这两个方法
    type Men interface {
        SayHi()
        Sing(lyrics string)
    }

    func main() {
        mike := Student{Human{"Mike", 25, "222-222-XXX"}, "MIT", 0}
        paul := Student{Human{"Paul", 26, "111-222-XXX"}, "Harvard", 100}
        sam := Employee{Human{"Sam", 36, "444-222-XXX"}, "Golang Inc.", 1000}
        tom := Employee{Human{"Tom", 37, "222-444-XXX"}, "Things Ltd.", 5000}

        //定义Men类型的变量i
        var i Men

        //i能存储Student
        i = mike
        fmt.Println("This is mike, a Student:")
        i.SayHi()
        i.Sing("November rain")

        //i也能存储Employee
        i = tom
        fmt.Println("This is tom, an Employee:")
        i.SayHi()
        i.Sing("Born to be wild")

        //定义了slice Men
        fmt.Println("Let's use a slice of Men and see what happens")
        x := make([]Men, 3)
        //这三个都是不同类型的元素,但是他们实现了interface同一个接口
        x[0], x[1], x[2] = paul, sam, mike

        for _, value := range x{
            value.SayHi()
        }
    }

  

原文地址:https://www.cnblogs.com/peterinblog/p/7843019.html