Adding methods to structs and implementing interfaces in Golang works a bit different compared to more object oriented languages like Java and PHP.
Where in PHP you would create a class with properties and add the methods "inside" the class, in Golang, the methods are added outside the struct code.
In PHP implementing interfaces and adding methods a like the example below:
<?php
interface Vat {
public function calculate(): int;
}
class Price implements Vat
{
public function calculate(): int
{
return 10;
}
}
class Product implements Vat
{
public function calculate(): int
{
return 20;
}
}
$pr1 = new Price();
$po1 = new Product();
$pr2 = new Price();
$po2 = new Product();
$list = [$pr1, $po1, $pr2, $po2];
foreach($list as $item) {
echo $item->calculate();
}
Golang does not require a struct to have an explicit implements of a given interfaces.
Adding a method with the same name as the method that is declared in an interface will allready imply that the struct implements the interface.
Below is a small code example where we demonstrate the above:
package main
import (
"fmt"
"strconv"
)
// Simple interface with one method Calculate
type vat interface {
Calculate() string
}
// go structs do not require the implements keyword to add the interface.
// implementing the methods, implies implementing the interface.
// Simple struct price
type price struct {
value int
}
// Simple struct product
type product struct {
value int
}
func (p *price) Calculate() string {
// Add the Calculate method to the price struct to "implement the interface".
// This is the way of adding methods to a struct.
return strconv.Itoa(p.value + 10)
}
func (p *product) Calculate() string {
// Add the Calculate method to the product struct to "implement the interface".
// This is the way of adding methods to a struct.
return strconv.Itoa(p.value + 10)
}
func main() {
// Create some instances of price and product.
pr1 := &price{value: 10}
po1 := &product{value: 20}
pr2 := &price{value: 30}
po2 := &product{value: 40}
// Add the instances to a slice as vat types.
vats := []vat{pr1, po1, pr2, po2}
// Loop over the slices
for _, vat := range vats {
// Print the result of the implemented method Calculate.
fmt.Println(vat.Calculate())
}
}
As you can see using interfaces and methods in Golang is a bit different than in other object oriented languages.
Both work pretty nice, once you are aware of how to implement them