go-learning/tour_of_go/l5/interfaces.go

41 lines
431 B
Go
Raw Permalink Normal View History

2025-08-31 16:38:50 +00:00
package main
import (
"fmt"
"math"
)
type MyFloat float64
type Vertex struct {
X, Y float64
}
type Abser interface {
Abs() float64
}
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
var a Abser
f := MyFloat(-math.Sqrt2)
v := Vertex{3, 4}
a = f
a = &v
// a = v
fmt.Println(a.Abs())
}