100daysofcode - Day 15
Hello folks, a new day and some new progress. In today’s post we will resume the technical content to dive more in Golang and explore some new amazing concepts. ![]()
![]()
In our last Golang post, we talked about pointers and their role and how we can use them with structs, functions, methods and more. ![]()
In today’s post we will talk about interfaces, their role and how we can utilize them. Starting from some theory
information and wrapping up with an example that shows us how we can use interfaces in a real example. ![]()
![]()
What is an interface in Golang ?
- An interface is a collection of method signatures that a Type can implement (using methods)

- The primary job of an interface is to provide only method signatures consisting of the method name, input arguments and return types

- If you are coming from an OOP environment, you might have used the implement keyword in many places, but when dealing with Golang there is no need to define it explicitly.

- To implement an interface in Golang we need to implement all the methods in the interface.

What happens if a struct does not implement all the interface methods ?
- In Golang when implementing an interface we should make sure that all methods are implemented. If not, we will receive an error

, showing us that we are missing a certain method.
- Example
package main
import (
"fmt"
"math"
)
// Here we are defining the interface geometry
// That define 2 signatures the area and perimeter in an abstract way
type geometry interface {
area() float64
perim() float64
}
// Here we have a rectangle struct with 2 attributes width and height
type rectangle struct {
width float64
height float64
}
// The circle struct with the radius attribute
type circle struct {
radius float64
}
// With the rectangle struct we are implementing the interface
// with all the signatures available inside of it
func (r rectangle) area() float64 {
return r.width * r.height
}
func (r rectangle) perim() float64 {
return 2*r.width + 2*r.height
}
// Same here for the circle functions that implement the geometry interface
func (c circle) area() float64 {
return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
return 2 * math.Pi * c.radius
}
// a generic measure function
func measure(g geometry) {
fmt.Println(g)
fmt.Println(g.area())
fmt.Println(g.perim())
}
func main() {
r := rectangle{width: 3, height: 4}
c := circle{radius: 5}
measure(r)
measure(c)
}
Now we reached the post end. In tomorrow’s post we will dive more into mixins and then we will introduce the functions concept, to utilize more the power of this amazing technology. ![]()
![]()