gobyexample/structs/structs.go
2024-04-27 11:15:44 +05:30

91 lines
1.4 KiB
Go

package structs
import (
"fmt"
"math"
)
type ShapeMetadata struct {
Id int
Name string
}
type Shape interface {
Area() float64
Perimeter() float64
}
type Square struct {
ShapeMetadata
Size float64
}
type Rectangle struct {
ShapeMetadata
Length, Breadth float64
}
type Triangle struct {
ShapeMetadata
A, B, C float64
}
func (s *Square) Area() float64 {
return s.Size * s.Size
}
func (s *Square) Perimeter() float64 {
return 4 * s.Size
}
func (r *Rectangle) Area() float64 {
return r.Length * r.Breadth
}
func (r *Rectangle) Perimeter() float64 {
return 2 * (r.Length + r.Breadth)
}
func (t *Triangle) Area() float64 {
s := (t.A + t.B + t.C) / 2
area := math.Sqrt(s * (s - t.A) * (s - t.B) * (s - t.C))
return area
}
func (t *Triangle) Perimeter() float64 {
return t.A + t.B + t.C
}
func Structs() {
sq := Square{
ShapeMetadata: ShapeMetadata{
Id: 0,
Name: "mysquare",
},
Size: 10.0,
}
rect := Rectangle{
ShapeMetadata: ShapeMetadata{
Id: 0,
Name: "myrectangle",
},
Length: 10,
Breadth: 5,
}
tri := Triangle{
ShapeMetadata: ShapeMetadata{
Id: 0,
Name: "mytriangle",
},
A: 2,
B: 2,
C: 2,
}
fmt.Printf("Triangle: Area = %.2f Perimeter = %.2f\n", tri.Area(), tri.Perimeter())
fmt.Printf("Rectangle: Area = %.2f Perimeter = %.2f\n", rect.Area(), rect.Perimeter())
fmt.Printf("Square: Area = %.2f Perimeter = %.2f\n", sq.Area(), sq.Perimeter())
}