dongqi6964 2019-04-12 20:38
浏览 190
已采纳

在Golang中实现相同接口的不同结构

I have an interface

type Shape interface {
    area() float32
    circumference() float32
}

I want to create different shapes such as a circle and a rectangle, for the circle I need to know the radius, and for the rectangle the 2 sides. So the code for each is like the following:

type DataCircle struct {
     radius float
}

(*DataCircle) area() float32 {
    return 3.14 * DataCircle.radius * DataCircle.radius;
}

(*DataCircle) circumference() float32 {
    return 2 * 3.14 * DataCircle.radius;
}

Similarly we have code for a rectangle which implement the interface Shape, with the following struct

type DataRectangle struct {
     side1 float
     side2 float
}

I want to create many different Rectangles and many different Circles, each one has different radius/sides. In the end I want to put them in a single array and be able to do something like the following

for _, shape := range all_shapes_in_array {
    fmt.Printf("%f %f", shape.area(), shape.circumference())
}

In a normal object oriented language this is pretty straight forward, but how do I do it in Golang?

  • 写回答

1条回答 默认 最新

  • doutian3269 2019-04-12 20:45
    关注

    As long as your DataCircle and DataRectangle structs implement the Shape interface you will be able to create an array/slice of type Shape and iterate through it.

    If you already have them implementing Shape then all you need to do is this:

    circle1 := &DataCircle{1}
    circle2 := &DataCircle{2}
    rec1 := &DataRectangle{1, 1}
    rec2 := &DataRectangle{4, 1}
    
    all_shapes_in_array := []Shape{circle1, circle2, rec1, rec2}
    for _, shape := range all_shapes_in_array {
        fmt.Printf("%f %f", shape.area(), shape.circumference())
    }
    

    And it will work as expected.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵