SilenceHVK / blog

:books: :octocat: Github static blog post, experience the fun of using Issues.Welcome star( 静态博客文章,体验一下使用 Issues 的乐趣,欢迎 star )个人博客地址:blog.hvkcoder.me/love
https://github.com/SilenceHVK/Articles/issues
MIT License
231 stars 9 forks source link

【Golang 基础】Go 语言的接口 #62

Open SilenceHVK opened 5 years ago

SilenceHVK commented 5 years ago

Go 语言中的接口

  Go 语言中的接口就是方法签名的集合,接口只有声明,没有实现,没有数据字段。

package main

import "fmt"

// 定义 Usb 接口
type Usb interface {
    GetName() string

    Connection()
}

// 定义 Phone 结构
type Phone struct {
    Name string
}

// 实现 Usb 接口的 GetName 方法
func (p Phone) GetName() string {
    return p.Name
}

// 实现 Usb 接口的 Connection 方法
func (p Phone) Connection() {
    fmt.Println("Connection:", p.GetName())
}

func main() {
    iPhone := Phone{Name:"iPhone"}

    fmt.Println(iPhone.GetName()) // iPhone
    iPhone.Connection()           // Connection:iPhone
}
iPhone := Phone{Name: "iPhone"}
var usb = Usb(iPhone)

fmt.Println(iPhone.GetName()) // iPhone
fmt.Println(usb.GetName())    // iPhone

iPhone.Name = "SAMSUNG"
fmt.Println(iPhone.GetName()) // SAMSUNG
fmt.Println(usb.GetName())    // iPhone
// 定义调用接口方法
func InvokInterface(inter interface{}) {
    // inter.(type) 用于获取类型
    switch t := inter.(type) {
        case Usb:
            t.Connection()
        case string:
            fmt.Println(t)
        default:
            fmt.Println("Unkown")
    }
}

function main() {
    iPhone := Phone{Name: "iPhone"}
    var usb = Usb(iPhone)

    hello := "Hello World"
    const PI = 3.14

    InvokerInterface(iPhone) // Connection: iPhone
    InvokerInterface(usb)    // Connection: iPhone
    InvokerInterface(hello)  // Hello World
    InvokerInterface(PI)     // Unkown
}