You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.1 KiB
Go

package structs
import "math"
// In Go interface resolution is implicit. So Rectangle and Cirle have
// receiver functions that satisfy the Shape interface.
type Shape interface {
Area() float64
}
type Rectangle struct {
Width float64
Height float64
}
type Circle struct {
Radius float64
}
type Triangle struct {
Base float64
Height float64
}
// There are examples of functions (not methods)
// Perimeter calculates the perimeter of a rectangle
func Perimeter(rectangle Rectangle) float64 {
return 2 * (rectangle.Width + rectangle.Height)
}
// Area calculates the area of a rectangle
func Area(rectangle Rectangle) float64 {
return rectangle.Width * rectangle.Height
}
// A method is a function with a receiver. A method declaration binds an identifier,
// the method name, to a method, and associates the method with the receiver's base type.
func (r Rectangle) Area() float64 {
return r.Height * r.Width
}
func (c Circle) Area() float64 {
return math.Pow(c.Radius, 2) * math.Pi
}
func (t Triangle) Area() float64 {
// return (t.Base * t.Height) / 2
return (t.Base * t.Height) * 0.5
}