Skip to content

Instantly share code, notes, and snippets.

@arriqaaq
Created January 27, 2023 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arriqaaq/00d2bd34cf4a10eb37b49c27d2738563 to your computer and use it in GitHub Desktop.
Save arriqaaq/00d2bd34cf4a10eb37b49c27d2738563 to your computer and use it in GitHub Desktop.
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