Structs
/* * Simple structure. */ package main import "fmt" import "math" /* * The type statement declares a type name. In this case, the struct. * A point. */ type Point struct { x, y float64 } /* * Passing a struct is usually by pointer, since otherwise it is copied. * (This is much like C.) But there is no separate -> operator. Use a dot * with either a struct or pointer to one. */ func distance(a *Point, b *Point) float64 { dx := a.x - b.x dy := a.y - b.y return math.Sqrt(dx*dx + dy*dy) } func main() { // Create a point by declaration. var origin Point // Initialized to zero values. fmt.Printf("(%g,%g)\n", origin.x, origin.y) var p1 Point = Point{4.8,-3.11} // Initialized by position p2 := Point{y: -3.0, x: 4.1} // Initialized by field name. fmt.Printf("(%g,%g) to (%g,%g) is %g\n", p1.x, p1.y, p2.x, p2.y, distance(&p1,&p2)) // Create using new. The new operator returns a pointer. var p3 *Point = new(Point) *p3 = Point{y: 3.2} var p4 *Point = new(Point) *p4 = Point{5.1,2.2} fmt.Printf("(%g,%g) to (%g,%g) is %g\n", p3.x, p3.y, p4.x, p4.y, distance(p3,p4)) }