41 lines
646 B
Go
41 lines
646 B
Go
package learning
|
|
|
|
import (
|
|
"fmt"
|
|
"math"
|
|
)
|
|
|
|
type InterfaceVertex struct {
|
|
X, Y float64
|
|
}
|
|
|
|
type Abser interface {
|
|
Abs() float64
|
|
}
|
|
|
|
func InterfaceLearning() {
|
|
var a Abser
|
|
f := MyFloat(-math.Sqrt2)
|
|
v := InterfaceVertex{3, 4}
|
|
|
|
a = f // a MyFloat implemets Abser
|
|
a = &v // a *InterfaceVertex implemets Abser
|
|
|
|
// In following line, v is InterfaceVertex (not *InterfaceVertex)
|
|
// and does NOT implement Abser
|
|
// a = v
|
|
fmt.Println(a.Abs())
|
|
}
|
|
|
|
type MyFloat float64
|
|
|
|
func (f MyFloat) Abs() float64 {
|
|
if f < 0 {
|
|
return float64(-f)
|
|
}
|
|
return float64(f)
|
|
}
|
|
|
|
func (v *InterfaceVertex) Abs() float64 {
|
|
return math.Sqrt(v.X*v.X + v.Y*v.Y)
|
|
}
|