组合接口而不定义新接口

问题描述 投票:0回答:1

在 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())
    
}
go syntax interface
1个回答
4
投票

接口可以嵌入其他接口。因此,您可以使用嵌入

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
的所有方法的所有类型的集合。

© www.soinside.com 2019 - 2024. All rights reserved.