Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "math"
- )
- type LengthComputer interface {
- Length() float64
- }
- type AngleComputer interface {
- Angle() float64
- }
- type Vector2 struct {
- x float64
- y float64
- }
- func (v Vector2) Length() float64 {
- return math.Sqrt(v.x*v.x + v.y*v.y)
- }
- func (v Vector2) Angle() float64 {
- return math.Atan2(v.y, v.x) * 180 / math.Pi
- }
- func main() {
- // if you declare/define "v" this way, it's OK
- var v LengthComputer = Vector2{-1, -1}
- // or like this... it works the same way
- //var v AngleComputer = Vector2{-1, -1}
- // However! this won't build,
- // says "./main.go:35:15: invalid type assertion: v.(LengthComputer) (non-interface type Vector2 on left)"
- // v := Vector2{-1, -1}
- if t, ok := v.(LengthComputer); ok {
- fmt.Printf("Type assertion for LengthComputer is %v, value = %v, length = %v\n", ok, t, t.Length())
- }
- if t, ok := v.(AngleComputer); ok {
- fmt.Printf("Type assertion for AngleComputer is %v, value = %v, angle (degrees) = %v\n", ok, t, t.Angle())
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement