首页 > 其他分享 >0093-Go-接口

0093-Go-接口

时间:2022-10-30 08:34:01浏览次数:67  
标签:float64 接口 height radius func Go 0093

环境

  • Time 2022-08-24
  • Go 1.19

前言

说明

参考:https://gobyexample.com/interfaces

目标

使用 Go 语言的接口。

定义接口

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

长方形实现接口

type rect struct {
    width, height float64
}

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

圆形实现接口

type circle struct {
    radius float64
}

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

接口方法

func measure(g geometry) {
    fmt.Println(g)
    fmt.Println(g.area())
    fmt.Println(g.perim())
}

使用

func main() {
    r := rect{width: 3, height: 4}
    c := circle{radius: 5}

    measure(r)
    measure(c)
}

总结

使用 Go 语言的接口。

附录

标签:float64,接口,height,radius,func,Go,0093
From: https://www.cnblogs.com/jiangbo4444/p/16840463.html

相关文章

  • 0094-Go-结构体嵌入
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/struct-embedding目标使用Go语言的结构体嵌入。定义结构体typebasestruct{numint......
  • 0095-Go-泛型
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/generics目标使用Go语言的泛型。泛型函数packagemainimport"fmt"funcMapKeys[Kcom......
  • 0075-Go-变量
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/variables目标使用Go语言变量的申明和使用变量。示例packagemainimport"fmt"funcma......
  • 0076-Go-常量
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/constants目标使用Go语言的常量。示例packagemainimport("fmt""math")co......
  • 0077-Go-for 循环
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/for目标使用Go语言的for循环。单条件循环类似其它语言中的while循环。packagemain......
  • 0078-Go-if else 条件判断
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/if-else目标使用Go语言的if/else条件判断。条件判断条件判断的小括号可以省略,但是后面的......
  • 0079-Go-switch 分支
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/switch目标使用Go语言的switch分支语句。整数分支packagemainimport"fmt"funcmai......
  • 0080-Go-数组
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/arrays目标使用Go语言的数组。申明数组packagemainimport"fmt"funcmain(){v......
  • 0081-Go-切片 slice
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/slices目标使用Go语言的切片类型。新建切片类型packagemainimport"fmt"funcmain()......
  • 0082-Go-关联类型 map
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/maps目标使用Go语言的关联类型map。新建mappackagemainimport"fmt"funcmain(){......