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 关于#自动化#的问题:如何通过电脑控制多相机同步拍照或摄影(相机或者摄影模组数量大于60),并将所有采集的照片或视频以一定编码规则存放至规定电脑文件夹内
  • ¥20 深信服vpn-2050这台设备如何配置才能成功联网?
  • ¥15 Arduino的wifi连接,如何关闭低功耗模式?
  • ¥15 Android studio 无法定位adb是什么问题?
  • ¥15 angular项目错误
  • ¥20 需要帮我远程操控一下,运行一下我的那个代码,我觉得我无能为力了
  • ¥20 有偿:在ubuntu上安装arduino以及其常用库文件。
  • ¥15 请问用arcgis处理一些数据和图形,通常里面有一个根据点划泰森多边形的命令,直接划的弊端是只能执行一个完整的边界,但是我们有时候会用到需要在有很多边界内利用点来执行划泰森多边形的命令
  • ¥30 在wave2foam中执行setWaveField时遇到了如下的浮点异常问题,请问该如何解决呢?
  • ¥750 关于一道数论方面的问题,求解答!(关键词-数学方法)