1
0
Fork 0
gotour-notes/methods/methods.go

42 lines
644 B
Go

package main
import (
"fmt"
)
type vertex struct {
x, y float64
}
// note that this one can deal fine with a copy:
func (v vertex) abs() float64 {
return v.x + v.y
}
// but this function needs access to the actual struct members
func (v *vertex) scale(s float64) {
v.x *= s
v.y *= s
}
type myfloat float64
func (f myfloat) abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
func main() {
v := vertex{1.1, 2.2}
fmt.Println(v.abs())
v.scale(12)
fmt.Println(v.abs())
f := myfloat(12.23)
fmt.Println(f.abs())
fmt.Println(-f)
fmt.Println((-f).abs())
}