2
0
mirror of https://github.com/chubin/cheat.sheets synced 2024-11-17 09:25:32 +00:00
cheat.sheets/sheets/_go/Structs
2020-10-15 18:29:27 +01:00

39 lines
1.0 KiB
Plaintext

// There are no classes, only structs. Structs can have methods.
// A struct is a type. It's also a collection of fields
// Declaration
type Vertex struct {
X, Y int
}
// Creating
var v = Vertex{1, 2}
var v = Vertex{X: 1, Y: 2} // Creates a struct by defining values with keys
var v = []Vertex{{1,2},{5,2},{5,5}} // Initialize a slice of structs
// Accessing members
v.X = 4
// You can declare methods on structs. The struct you want to declare the
// method on (the receiving type) comes between the func keyword and
// the method name. The struct is copied on each method call(!)
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
// Call method
v.Abs()
// For mutating methods, you need to use a pointer (see below) to the Struct
// as the type. With this, the struct value is not copied for the method call.
func (v *Vertex) add(n float64) {
v.X += n
v.Y += n
}
// **Anonymous structs:**
// Cheaper and safer than using `map[string]interface{}`.
point := struct {
X, Y int
}{1, 2}