在 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
和 appearance
的匿名接口类型,如下所示:
func measure(g interface {
geometry
appearance
}) {
fmt.Println(g)
fmt.Println(g.area()) // Method defined by geometry
fmt.Println(g.perim()) // Method defined by geometry
fmt.Println(g.color()) // Method defined by appearance
}
这在规格:接口类型:
中有详细介绍嵌入式接口
在稍微更一般的形式中,接口
可以使用(可能限定的)接口类型名称T
作为接口元素。这在E
E
中称为embedding接口。T
的类型集是T
T
显式声明的方法定义的类型集与的嵌入式接口的类型集的T
交集。换句话说,的类型集是实现T
的所有显式声明的方法以及T
的所有方法的所有类型的集合。E