登录
首页 >  Golang >  Go问答

golang 接口中是否可以有可选方法?

来源:stackoverflow

时间:2024-04-30 21:18:33 290浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《golang 接口中是否可以有可选方法?》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

问题内容

我想为界面创建可选的 perim 方法。有可能吗?就像我不想为三角形创建 perim 方法,但它给了我缺少一种方法的错误。接口中是否可以有可选方法?

请告诉我它的替代方案或某种解决方案。

type geometry interface {
    area() float64
    perim() float64
}

type rect struct {
    width, height float64
}

type triangle struct {
    base, height float64
}

type circle struct {
    radius float64
}

type square struct {
    side float64
}

func (r rect) area() float64 {
    return r.width * r.height
}

func (r rect) perim() float64 {
    return 2*r.width + 2*r.height
}

func (c circle) area() float64 {
    return math.Pi * c.radius * c.radius
}

func (c circle) perim() float64 {
    return 2 * math.Pi * c.radius
}

func (t triangle) area() float64 {
    return 1 / 2 * t.base * t.height
}

func measure(g geometry) {
    fmt.Println(g)
    switch g.(type) {
    case rect:
        fmt.Println("Rectangles area :", g.area())
        fmt.Println("Rectangle perimeter: ", g.perim())
    case circle:
        fmt.Printf("Circles Area: %.2f\n", g.area())
        fmt.Printf("Circles Perimeter: %.2f\n", g.perim())
    case square:
        fmt.Printf("Area of square: %.2f\n", g.area())
        fmt.Printf("Perimeters of area: %.2f\n", g.perim())
    case triangle:
        fmt.Printf("Area of  triangle: %.2f\n", g.area())
    }
}

func main() {
    r := rect{width: 3, height: 4}
    c := circle{radius: 5}
    s := square{side: 7}
    t := triangle{base: 3, height: 4}
    measure(r)
    measure(c)
    measure(s)
    measure(t)
}

正确答案


规范不允许“标记”方法在 interface 类型中可选。

请注意,您的实现可能会提供其他方法,而不仅仅是您要实现的接口的一部分的方法。 Type assertion 可用于检查值的具体类型是否具有“附加”方法,方法是检查它们是否实现具有这些附加方法的接口类型。

在此示例中,fooimpl 仅具有方法 one(),但 foo2impl 具有方法 one()two()

type foo interface {
    one()
}

type fooimpl int

func (fi fooimpl) one() {}

type foo2impl int

func (fi foo2impl) one() {}
func (fi foo2impl) two() {}

func check(f foo) {
    if ft, ok := f.(interface{ two() }); ok {
        fmt.printf("%t(%v) has method two()\n", f, f)
        ft.two() // you can call it
    } else {
        fmt.printf("%t(%v) doesn't have method two()\n", f, f)
    }
}

func main() {
    check(fooimpl(1))
    check(foo2impl(2))
}

它的输出(在Go Playground上试试):

main.fooimpl(1) doesn't have method two()
main.foo2impl(2) has method two()

您当然可以使用这些附加方法创建接口类型:

type bar interface {
    two()
}

然后检查它:

if ft, ok := f.(Bar); ok {
    fmt.Printf("%T(%v) has method Two()\n", f, f)
    ft.Two() // You can call it
} else {
    fmt.Printf("%T(%v) doesn't have method Two()\n", f, f)
}

拨打 Go Playground 试试这个。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>