/*
* Simple structure.
*/
package main
import "fmt"
import "math"
/*
* The Point again.
*/
type Point struct {
x, y float64
}
/*
* Go allows methods to declare a "receiver," which allows them to be
* called as methods of the recevier's type.
*/
func (p *Point) to_s() string {
return fmt.Sprintf("(%g,%g)", p.x, p.y)
}
func (from *Point) distance(to *Point) float64 {
dx := from.x - to.x
dy := from.y - to.y
return math.Sqrt(dx*dx + dy*dy)
}
func main() {
// Create a point by declaration.
var origin Point
fmt.Println(origin.to_s())
var p1 Point = Point{4.8,-3.11}
p2 := Point{y: -3.0, x: 4.1}
fmt.Println(p1.to_s(), "to", p2.to_s(), "is", p1.distance(&p2))
var p3 *Point = new(Point)
*p3 = Point{y: 3.2}
var p4 *Point = new(Point)
*p4 = Point{5.1,2.2}
fmt.Println(p3.to_s(), "to", p4.to_s(), "is", p3.distance(p4))
}
Go allows a function to specify a receiver. This an extra argument
which is specified before the function name, and is sent to the function
by calling it with the dot notation, as is familiar for methods.
The receiver:
- The receiver parameter is a pointer type
- The argument need not be a pointer, in which case a pointer is
sent anyway
- The function may be overloaded on the recevier type. (Go functions
may not be overloaded on general parameter types.)