Skip to content

Instantly share code, notes, and snippets.

@incon
Created September 19, 2024 02:45
Show Gist options
  • Save incon/12037f9e8702ed74261711b92cb6dc42 to your computer and use it in GitHub Desktop.
Save incon/12037f9e8702ed74261711b92cb6dc42 to your computer and use it in GitHub Desktop.
Example `self` in Go
package main
import (
"fmt"
"math"
)
// Any local type
type Vertex struct {
X, Y float64
}
// Returns result only
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
// This is a pointer receiver `*Vertex` known as self in other programming languages
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func main() {
v := Vertex{3, 4}
v.Scale(10)
fmt.Println(v.Abs())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment