Created
September 19, 2024 02:45
-
-
Save incon/12037f9e8702ed74261711b92cb6dc42 to your computer and use it in GitHub Desktop.
Example `self` in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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