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

在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?

图片转代码服务由CSDN问答提供 功能建议

我有一个界面

  type Shape interface {
  area()float32 
圆周()float32 
} 
   
 
 

我想创建不同的形状,例如圆形和矩形,对于该圆形,我需要 知道半径,矩形知道2边。 因此,每个代码都如下所示:

  type DataCircle struct {
 radius float 
} 
 
(* DataCircle)area()float32 {
 返回3.14 * DataCircle.radius * DataCircle.radius; 
} 
 
(* DataCircle)圆周()float32 {
返回2 * 3.14 * DataCircle.radius; 
} 
   
 
 

类似地,我们有一个矩形的代码,实现了Shape的接口,并带有以下结构

  type DataRectangle struct {
 side1 float 
 side2  float 
} 
   
 
 

我想创建许多不同的矩形和许多不同的圆,每个圆都有不同的半径/边。 最后,我想将它们放在一个数组中,并能够对_,shape:= range all_shapes_in_array { fmt.Printf( “%f%f”,shape.area(),shape.circumference()) }

在普通的面向对象语言中,这非常简单 ,但是如何在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.

    点赞 评论

相关推荐 更多相似问题