Skip to content

Object Orientated Programming

Methods

A method on OOP is a function associated with an invocation object or in Go a variable.

Example of a function:

var num int

func isEven(num int) bool {
    return num%2==0
}

result := isEven(myNum)

A method in Go starts with a custom type, but doesn't need to be a struct. Notice the method receiver in the following function definition (which makes it a method). This means the following method is restricted to only work with a specific type:

type myNum int

var yob myNum

func (num myNum) isEven() bool {
    return int(num)%2==0
}

result = yob.isEven()

The difference between a function and a method is subtle, but methods indicate a tighter coupling between a function and a type.

Method receivers can use values or pointers:

type user struct {
    id          int
    username    string
}

func (u user) String() string{
    return fmt.Sprintf("%v (%v)\n", u.username, u.id)
}

func (u *user) UpdateName(n name) {
    u.username = name
}

Interfaces

Unlike a struct, we define the behaviors of an interface, or put another way, model the methods.

type Reader interface {
    Read([]byte) (int, error)
}

type File struct { ... }
func (f File)Read(b []byte) (n int, err error)

type TCPConn struct { ... }
func (f TCPConn)Read(b []byte) (n int, err error)

var f File
var t TCPConn

var r Reader

r = f
r.Read(...)
r = t
r.Read(...)

Type assertion:

f = r.(File)
f, ok := r.(File)

Type switches:

var f File
var r Reader = f

switch v := r.(type) {
    case File:
        // Do stuff as File object
    case TCPConn:
        // Do stuff as TCPConn object
    default:
        // Catch all
}

Example:

package main

type message interface {
    Print() string
}

type player struct {
    name    string
    health  int
}

func (p player) Print() string {
    return fmt.Sprintf("%v [%v]\n", p.name, p.health)
}

func main() {

}

Generic Programming