Arn*_* C. 1 syntax interface go
在 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())
}
Run Code Online (Sandbox Code Playgroud)
接口可以嵌入其他接口。geometry因此,您可以使用嵌入和的匿名接口类型,appearance如下所示:
func measure(g interface {\n geometry\n appearance\n}) {\n fmt.Println(g)\n fmt.Println(g.area()) // Method defined by geometry\n fmt.Println(g.perim()) // Method defined by geometry\n fmt.Println(g.color()) // Method defined by appearance\n}\nRun Code Online (Sandbox Code Playgroud)\n规范:接口类型中有详细说明:
\n\n\n嵌入式接口
\n在稍微更一般的形式中,接口
\nT可以使用(可能限定的)接口类型名称E作为接口元素。这在.ET 的类型集T是由显式声明的方法定义的类型集与\xe2\x80\x99s 嵌入接口的类型集的交集。换句话说, 的类型集是实现 的所有显式声明的方法以及 的所有方法的所有类型的集合TTTTE。