Skip to content

Instantly share code, notes, and snippets.

@cc2011
Last active May 23, 2016 03:33
Show Gist options
  • Save cc2011/4422364c86783916f1095d48916cc07f to your computer and use it in GitHub Desktop.
Save cc2011/4422364c86783916f1095d48916cc07f to your computer and use it in GitHub Desktop.
Struct Golang
Two ways to initialize struct
=============================
First Form
===========
type Point struct{ X, Y int }
p := Point{1, 2}
Second Form
===========
The second form is used, in which a struct value is initialized by listing some or all of the field names and their corresponding values, as in this statement from the Lissajous program of Section 1.4:
anim := gif.GIF{LoopCount: nframes}
package p
type T struct{ a, b int } // a and b are not exported
package q
import "p"
var _ = p.T{a: 1, b: 2} // compile error: can't reference a, b
var _ = p.T{1, 2} // compile error: can't reference a, b
Struct values can be passed as arguments to functions and returned from them. For instance, this function scales a Point by a specified factor:
func Scale(p Point, factor int) Point {
return Point{p.X * factor, p.Y * factor}
}
fmt.Println(Scale(Point{1, 2}, 5)) // "{5 10}"
For efficiency, larger struct types are usually passed to or returned from functions indirectly using a pointer,
func Bonus(e *Employee, percent int) int {
return e.Salary * percent / 100
}
pp := &Point{1, 2} ===== pp := new(Point) *pp = Point{1,2}
Comparable struct types, like other comparable types, may be used as the key type of a map.
type address struct {
hostname string
port int
}
hits := make(map[address]int)
hits[address{"golang.org", 443}]++
type Wheel struct {
X, Y, Radius, Spokes int
}
var w Wheel
w.X = 8
w.Y = 8
w.Radius = 5
w.Spokes = 20
struct Embedding
================
type Point struct {
X, Y int
}
type Circle struct {
Center Point
Radius int
}
type Wheel struct {
Circle Circle
Spokes int
}
var w Wheel
w.Circle.Center.X = 8
w.Circle.Center.Y = 8
w.Circle.Radius = 5
w.Spokes = 20
VS
Go lets us declare a field with a type but no name; such fields are called anonymous fields. The type of the field must be a named type or a pointer to a named type. Below, Circle and Wheel have one anonymous field each. We say that a Point is embedded within Circle, and a Circle is embedded within Wheel.
type Circle struct {
Point
Radius int
}
type Wheel struct {
Circle
Spokes int
}
var w Wheel
w.X = 8 // equivalent to w.Circle.Point.X = 8
w.Y = 8// equivalent to w.Circle.Point.Y = 8
w.Radius = 5 // equivalent to w.Circle.Radius = 5
w.Spokes = 20
Unfortunately, there’s no corresponding shorthand for the struct literal syntax, so neither of these will compile:
w = Wheel{8, 8, 5, 20} // compile error: unknown fields
w = Wheel{X: 8, Y: 8, Radius: 5, Spokes: 20} // compile error: unknown fields
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment