https://inasa.dev/blog/rss.xml

Go | 接口完整性检查

2024-03-10
type Shape interface {
    Sides() int
    Area() int
}
type Square struct {
    len int
}
func (s* Square) Sides() int {
    return 4
}
var _ Shape = (*Square)(nil)
func main() {
    s := Square{len: 5}
    fmt.Printf("%d\n",s.Sides())
}

声明一个_变量(用不到),其会把一个nil的空指针,从Square转成Shape,这样,如果没有实现完相关的接口方法,编译器就会报错:

cannot use (*Square)(nil) (type *Square) as type Shape in assignment: *Square does not implement Shape (missing Area method)