I am a developer with a passion for testing. I've been coding for 14 years and I want to share my experience and learnings with other developers to help them write better software.
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.
packagemainimport("fmt""math")typegeometryinterface{area()float64perimeter()float64}typecirclestruct{radiusfloat64}typerectanglestruct{width,heightfloat64}// implementing the interface methodsfunc(ccircle)area()float64{returnmath.Pi*c.radius*c.radius}func(ccircle)perimeter()float64{return2*math.Pi*c.radius}func(rrectangle)area()float64{returnr.width*r.height}func(rrectangle)perimeter()float64{return2*r.width+2*r.height}// we can call methods that are in the named interfacefuncmeasure(ggeometry){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 measurefuncmain(){r:=rect{width:3,height:4}c:=circle{radius:5}measure(r)measure(c)}
I am a developer with a passion for testing. I've been coding for 14 years and I want to share my experience and learnings with other developers to help them write better software.
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.Here's an awesome reference to learn more about Interfaces in Go jordanorelli.com/post/32665860244/...
Thank you that is really useful.
It is said that Go doesn't have "generics" but these look pretty much like generics:
func (r rectangle) area()
func (c circle) area()
talking about user defined generics not built inπ