DEV Community

Discussion on: How I learned Go Programming

Collapse
 
robdwaller profile image
Rob Waller

I've started to learn Go, however am struggling with interfaces, particularly compared to how they work in dynamically typed languages like PHP, any tips?

Collapse
 
codehakase profile image
Francis Sunday

Interfaces in OOP, enforce definition of some set of method in the class. By implementing interfaces, you are forcing any class to declaring some specific set of methods.

Interfaces in Go can be seen as named collections of method signatures.

For instance, a Geometry interface in go both Circles and Rectangles can implement the same Interface, but they must implement all the methods of that interface.

package main
import (
  "fmt"
  "math"
)

type geometry interface {
  area() float64
  perimeter() float64
}

type circle struct {
  radius float64
}

type rectangle struct {
  width, height float64
}

// implementing the interface methods

func (c circle) area() float64 {
    return math.Pi * c.radius * c.radius
}
func (c circle) perimeter() float64 {
    return 2 * math.Pi * c.radius
}

func (r rectangle) area() float64 {
  return r.width * r.height
}

func (r rectangle) perimeter() float64 {
  return 2*r.width + 2*r.height
}

// we can call methods that are in the named interface

func measure(g geometry) {
    fmt.Println(g)
    fmt.Println(g.area())
    fmt.Println(g.perimiter())
}

// The circle and rectangle struct types both implement the geometry
// interface so we can use instances of these structs as arguments 
// to measure

func main() {
  r := rect{width: 3, height: 4}
  c := circle{radius: 5}

  measure(r)
  measure(c)
}

Here's an awesome reference to learn more about Interfaces in Go jordanorelli.com/post/32665860244/...

Collapse
 
robdwaller profile image
Rob Waller

Thank you that is really useful.

Collapse
 
casperbraske profile image
Luis

It is said that Go doesn't have "generics" but these look pretty much like generics:

func (r rectangle) area()

func (c circle) area()

Thread Thread
 
baksman profile image
ibrahim Shehu

talking about user defined generics not built inπŸ˜ƒ