Go doest not support classes. To, define methods that works on a certain type, we use methods [= function + receiver
].
receiver
argument is a instance of the type the method works on.
Scale
method operates on a copy of the original Vertex
value. (This is the same behaviour as for any other function argument.) See how Abs
method works on a copy of the original Vertex
value, while Scale
method works on the value to which the receiver points.Go interprets the statement v.Scale(5)
as (&v).Scale(5)
since the Scale
method has a pointer receiver.
In this case, the method call p.Abs()
is interpreted as (*p).Abs()
.
<aside> 💡 In general, all methods on a given type should have either value or pointer receivers, but not a mixture of both.
</aside>
It defines a set of method signatures (names, input parameters, and return types) that a type must implement to satisfy the interface.
type Shape interface {
Area() float64
Perimeter() float64
}
This declares a Shape
interface with two methods: Area()
and Perimeter()
. Any type that wants to be considered a "shape" must implement both of these methods.
type Rectangle struct {
width, height float64
}
func (r Rectangle) Area() float64 {
return r.width * r.height
}
func (r Rectangle) Perimeter() float64 {
return 2*r.width + 2*r.height
}
// ... similar implementations for Circle, Triangle, etc.
func PrintShapeInfo(s Shape) {
fmt.Println("Area:", s.Area())
fmt.Println("Perimeter:", s.Perimeter())
}
rect := Rectangle{width: 5, height: 10}
PrintShapeInfo(rect)