Define the interface
Interfaces are named collections of method signatures.
Code Block |
---|
package main
import (
"fmt"
"math"
)
type geometry interface {
area() float64
perim() float64
}
type rect Greet(username string)
} |
Create an Object(struct and functions) that will implement the interface.
Code Block |
---|
type NiceGreeter struct {}
func (g NiceGreeter) width, height float64
}
type circleGreet(username string){
fmt.Printf("Hi %s ",username)
} |
In the above, we can see that we simply implement the function of the interface.
We link the type (Object) to the function using (db DefaultDatabse) in the above code.
Use the interface
Define an Object(struct) that uses the interface
Code Block |
---|
type Program struct {
radius float64 Greeter Greeter
}
func (rp rectProgram) areaExecute(user string) float64 {
p.Greeter.Greet(user)
} |
Code Block |
---|
func main(){
//instantiate the greeter that implements Greeter
greeter := NiceGreeter{}
//instantiate the program with our greeter
p:= Program{
Greeter: greeter,
}
//execute
p.Execute("bob")
} |
Full Code Example
Code Block |
---|
package main
import "fmt"
type Greeter interface {
Greet(username string)
}
type NiceGreeter struct {}
func (g NiceGreeter) Greet(username string){
fmt.Printf("Hi %s ",username)
}
type Program struct {
Greeter Greeter
}
func (p Program) Execute(user string){
p.Greeter.Greet(user)return r.width * r.height
}
func (r rect) perim() float64 {
return 2*r.width + 2*r.height
}
func (c circle) area() float64 {
return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
return 2 * math.Pi * c.radius
}
func measure(g geometry) {
fmt.Println(g)
fmt.Println(g.area())
fmt.Println(g.perim())
}
func main() {
r
greeter := rect{width: 3, height: 4}
c NiceGreeter{}
p:= circle{radiusProgram{
Greeter: 5}
measure(r)
measure(cgreeter,
}
p.Execute("bob")
} |
References