Advertisement
drpanwe

interfaces.go

Apr 9th, 2019
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.06 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. // Shape of thing (e.g. square)
  6. type Shape interface {
  7.     // Signature of functions that implement this interface
  8.     Area() float64
  9.     Perimeter() float64
  10. }
  11.  
  12. // Different types of shapes:
  13. type square struct {
  14.     X float64
  15. }
  16.  
  17. // Area() implementation (see the name of the function) for the Shape interface of the square type (as a receiver)
  18. // receiver.field accesses the fields of the struct
  19. func (s square) Area() float64 {
  20.     return s.X * s.X
  21. }
  22.  
  23. // Perimeter() implementation (see the name) for the Shape interface of the square type (as a receiver)
  24. // receiver.field accesses the fields of the struct
  25. func (s square) Perimeter() float64 {
  26.     return 4 * s.X
  27. }
  28.  
  29. // Calculate the shape of a thing (area and perimeter)
  30. // Function using the interface Shape (see the input) -- has no output
  31. func Calculate(x Shape) {
  32.     v, ok := x.(square)
  33.     if ok {
  34.         fmt.Println("Is a square:", v)
  35.     }
  36.  
  37.     fmt.Println(x.Area())
  38.     fmt.Println(x.Perimeter())
  39. }
  40.  
  41. func main() {
  42.     x := square{X: 10}
  43.     fmt.Println("Perimeter:", x.Perimeter())
  44.     Calculate(x)
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement