在 go 中,您可以将内联接口与函数签名结合起来吗?还是不可能,唯一的选择是创建第三个接口来组合较小的接口?
// _Interfaces_ are named collections of method
// signatures.
package main
import (
"fmt"
"math"
)
// Here's a basic interface for geometric shapes.
type geometry interface {
area() float64
perim() float64
}
type appearance interface {
color() string
texture() string
}
// For our example we'll implement this interface on
// `rect` and `circle` types.
type rect struct {
width, height float64
}
type circle struct {
radius float64
}
// To implement an interface in Go, we just need to
// implement all the methods in the interface. Here we
// implement `geometry` on `rect`s.
func (r rect) area() float64 {
return r.width * r.height
}
func (r rect) perim() float64 {
return 2*r.width + 2*r.height
}
// The implementation for `circle`s.
func (c circle) area() float64 {
return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
return 2 * math.Pi * c.radius
}
// can I combine interfaces in line here without creating a third interface that combines geometry and appearance.
func measure(g {geometry appearance}) {
fmt.Println(g)
fmt.Println(g.area())
fmt.Println(g.perim())
}
接口可以嵌入其他接口。因此,您可以使用嵌入
geometry
和外观`的匿名接口类型,如下所示:
func measure(g interface {
geometry
appearance
}) {
fmt.Println(g)
fmt.Println(g.area())
fmt.Println(g.perim())
}