去组合接口

问题描述 投票: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())
    
}
function go syntax interface
1个回答
0
投票

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

geometry
和外观`的匿名接口类型,如下所示:

func measure(g interface {
    geometry
    appearance
}) {
    fmt.Println(g)
    fmt.Println(g.area())
    fmt.Println(g.perim())
}
© www.soinside.com 2019 - 2024. All rights reserved.