Go cheatsheet - difference between Go method and regular function

difference between Go method and regular function

A method is just a function with a special receiver argument that defined on types.

Go method

package main

import (
	"fmt"
	"math"
)

type Vertex struct {
	X, Y float64
}

//  define methods on Vertex
func (v Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
	v := Vertex{3, 4}
	fmt.Println(v.Abs())
}

Go regular function

package main

import (
	"fmt"
	"math"
)

type Vertex struct {
	X, Y float64
}

// regular function
func Abs(v Vertex) float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
	v := Vertex{3, 4}
	fmt.Println(Abs(v))
}
Date: From:www.lautturi.com, cheatsheet