A Go Interface as used in structs

      A Go Interface as used in structs

      This is an example of implementing an interface in Go.

      Go code

      1. package main
      2. import "fmt"
      3. type car struct {
      4. make string
      5. model string
      6. }
      7. type truck struct {
      8. make string
      9. model string
      10. }
      11. type reader interface {
      12. printVehicle()
      13. }
      14. func main() {
      15. ford := car{"Ford", "Capri"}
      16. volvo := truck{"Volvo", "VHD"}
      17. readInfo(ford) // see output at the bottom
      18. readInfo(volvo) // see output at the bottom
      19. }
      20. func (t truck) printVehicle() {
      21. fmt.Println("This is a truck: ")
      22. fmt.Printf("Make: %s\tModel: %s\n", t.make, t.model)
      23. }
      24. func (c car) printVehicle() {
      25. fmt.Println("This is a car: ")
      26. fmt.Printf("Make: %s\tModel: %s\n", c.make, c.model)
      27. }
      28. func readInfo(r reader) {
      29. r.printVehicle()
      30. }
      31. /*
      32. This is a car:
      33. Make: Ford Model: Capri
      34. This is a truck:
      35. Make: Volvo Model: VHD
      36. */


      • On lines 5 through 12 two structs were declared: car and truck. Each struct has its own method named printVehicle (lines 27 through 35).
      • We also have an interface named reader (lines 14 through 16), which lists the printVehicle method as a prerequisite for membership.
      • Since the interface reader is just a description of an implementation, the real implementation comes from the function readInfo (lines 37 through 39), which takes a member of type reader as an argument, and invokes the correct printVehicle function for this argument.

      Notice how neither type (car or truck) explicitly implement interface reader. Interfaces are satisfied implicitly and multiple types can use such interface.

      Notice also, how types ford and volvo, which are instances of their respective types (car and truck), can also implement interface reader.
      ---------------------------
      New eBook release: Go Exercises in Plain Language, Volume 1, Volume 2, Volume 3
      New eBook release: TypeScript in Plain Language Volume I | Volume 2 with Angular 4
      New quick read: The Factorial Recursive Function: A language agnostic explanation with samples in Go and JavaScript.
      - Please subscribe my Twitter or my Amazon profile to be notified of new releases.
      Author's profile on Amazon
      Twitter
      TonyAr