Methods in Go

Methods are functions which have a receiver argument (belonging to a predefined type).

func (variableName typeName) methodName(paramName paramType) (returnVarName returnType) {
    //some operation, usually on fields of the type

//methods are called on the variable of its type
variableName := typeName{ values for struct }


Methods are typically used to emulate class-like behavior on struct types. Methods do not have to receive a struct type.

Pointers can also be receiving types for methods.

Methods behave exactly the same as functions.

package main

import "fmt"

type Degrees struct {
    angle float64

func (deg Degrees) toRad() float64 {
    return deg.angle * (3.14 / 180.0)

func main() {
    angle := Degrees { 90.0 }
    fmt.Println("Angle, in radians: ", angle.toRad())

< Closures   |   Interfaces >

© 2019 SyntaxDB. All Rights Reserved.