Created
January 27, 2023 09:42
-
-
Save arriqaaq/00d2bd34cf4a10eb37b49c27d2738563 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
// Shape is the interface that all shapes must implement | |
type Shape interface { | |
Area() float64 | |
} | |
// Rectangle represents a rectangle shape | |
type Rectangle struct { | |
Width float64 | |
Height float64 | |
} | |
// Area calculates the area of a rectangle | |
func (r *Rectangle) Area() float64 { | |
return r.Width * r.Height | |
} | |
// Circle represents a circle shape | |
type Circle struct { | |
Radius float64 | |
} | |
// Area calculates the area of a circle | |
func (c *Circle) Area() float64 { | |
return 3.14159 * c.Radius * c.Radius | |
} | |
// CompositeShape represents a composite shape that can contain other shapes | |
type CompositeShape struct { | |
Shapes []Shape | |
} | |
// Area calculates the area of a composite shape by summing the areas of its child shapes | |
func (c *CompositeShape) Area() float64 { | |
var area float64 | |
for _, shape := range c.Shapes { | |
area += shape.Area() | |
} | |
return area | |
} | |
func main() { | |
rect := &Rectangle{Width: 10, Height: 5} | |
circle := &Circle{Radius: 3} | |
composite := &CompositeShape{Shapes: []Shape{rect, circle}} | |
fmt.Println("Area of composite shape:", composite.Area()) // prints "Area of composite shape: 34.9159" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment