Quidest?

Go types and methods

· Lorenzo Drumond

It’s quite common to deal with things in our programs that represent objects or entities in the real world.

We use Go’s struct keyword to define types to represent objects like this in Go programs.

E.g.:

1type Book struct {
2    Title  string
3    Author string
4    Copies int
5    ID     int
6    PriceCents int
7    DiscountPercent int
8}

structs allow us to define properties of an object in the form of fields: static information that defines the object.

However objects have also behaviours that we may want to represent; that is, some logic in the form of code that produces dynamic results.

We could write functions that take a struct as parameter and perform actions on its fields. This is common enough that Go has a shorthand for this: methods:

1book.SomeAction()

A method in Go is defined similarly to a function, but we need to specify a receiver: that is, the object that owns the method:

1func (b Book) NetPriceCents() int {
2    saving := b.PriceCents * b.DiscountPercent / 100
3    return b.PriceCents - saving
4}

A method is a function with a special receiver argument.

The receiver appears in its own argument list between the func keyword and the method name.

 1package main
 2
 3import (
 4	"fmt"
 5	"math"
 6)
 7
 8type Vertex struct {
 9	X, Y float64
10}
11
12func (v Vertex) Abs() float64 {
13	return math.Sqrt(v.X*v.X + v.Y*v.Y)
14}
15
16func main() {
17	v := Vertex{3, 4}
18	fmt.Println(v.Abs())
19}

References

Next -> go-struct-wrappers

Next -> go-methods-on-non-local-types

Next -> methods-on-non-struct-types

#non_local #golang #methods #programming #types #receiver