re: How I learned Go Programming VIEW POST

FULL DISCUSSION
 

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?

 

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/...

 
 

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

func (r rectangle) area()

func (c circle) area()

code of conduct - report abuse