mirror of
https://github.com/alrayyes/wiki.git
synced 2024-12-01 15:26:23 +00:00
64 lines
926 B
Markdown
64 lines
926 B
Markdown
---
|
|
id: 03a6cd46-e6fb-46a8-96f7-16c37a6d140a
|
|
title: Golang methods
|
|
---
|
|
|
|
# Basics
|
|
|
|
In Go methods can be defined on [struct](20200828181259-structs) and
|
|
non-struct types. In this case a **receiver** argument ias passed
|
|
between \`func\` keyword and the method name (\`Abs\`):
|
|
|
|
``` go
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"math"
|
|
)
|
|
|
|
type Vertex struct {
|
|
X, Y float64
|
|
}
|
|
|
|
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())
|
|
}
|
|
```
|
|
|
|
# Pointers
|
|
|
|
To modify struct values methods must be declared with pointer receivers:
|
|
|
|
``` go
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"math"
|
|
)
|
|
|
|
type Vertex struct {
|
|
X, Y float64
|
|
}
|
|
|
|
func (v Vertex) Abs() float64 {
|
|
return math.Sqrt(v.X*v.X + v.Y*v.Y)
|
|
}
|
|
|
|
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())
|
|
}
|
|
```
|