Ensure a type implements an interface at compile time in Go

后端 未结 6 1407
悲&欢浪女
悲&欢浪女 2020-11-30 08:51

How can I ensure that a type implements an interface at compile time? The typical way to do this is by failure to assign to support interfaces from that type, however I have

6条回答
  •  野性不改
    2020-11-30 09:37

    package main
    
    import (
        "fmt"
    )
    
    type Sayer interface {
        Say()
    }
    
    type Person struct {
        Name string
    }
    
    func(this *Person) Say() {
        fmt.Println("I am", this.Name)
    }
    
    func main() {
        person := &Person{"polaris"}
    
        Test(person)
    }
    
    func Test(i interface{}) {
        //!!here ,judge i implement Sayer
        if sayer, ok := i.(Sayer); ok {
            sayer.Say()
        }
    }
    

    The code example is here:http://play.golang.org/p/22bgbYVV6q

提交回复
热议问题