Advertisement
mbazs

Go polymorphism

Jul 13th, 2020
1,580
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.02 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "math"
  6. )
  7.  
  8. type LengthComputer interface {
  9.     Length() float64
  10. }
  11.  
  12. type AngleComputer interface {
  13.     Angle() float64
  14. }
  15.  
  16. type Vector2 struct {
  17.     x float64
  18.     y float64
  19. }
  20.  
  21. func (v Vector2) Length() float64 {
  22.     return math.Sqrt(v.x*v.x + v.y*v.y)
  23. }
  24.  
  25. func (v Vector2) Angle() float64 {
  26.     return math.Atan2(v.y, v.x) * 180 / math.Pi
  27. }
  28.  
  29. func main() {
  30.     // if you declare/define "v" this way, it's OK
  31.     var v LengthComputer = Vector2{-1, -1}
  32.     // or like this... it works the same way
  33.     //var v AngleComputer = Vector2{-1, -1}
  34.  
  35.     // However! this won't build,
  36.     // says "./main.go:35:15: invalid type assertion: v.(LengthComputer) (non-interface type Vector2 on left)"
  37.     // v := Vector2{-1, -1}
  38.  
  39.     if t, ok := v.(LengthComputer); ok {
  40.         fmt.Printf("Type assertion for LengthComputer is %v, value = %v, length = %v\n", ok, t, t.Length())
  41.     }
  42.     if t, ok := v.(AngleComputer); ok {
  43.         fmt.Printf("Type assertion for AngleComputer is %v, value = %v, angle (degrees) = %v\n", ok, t, t.Angle())
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement