Skip to content

Instantly share code, notes, and snippets.

@donvito
Created October 29, 2019 01:19
Show Gist options
  • Save donvito/e5676000976caa3d613df13cd7df76cf to your computer and use it in GitHub Desktop.
Save donvito/e5676000976caa3d613df13cd7df76cf to your computer and use it in GitHub Desktop.
Go Interface example - print area of shapes
package main
import (
"fmt"
"reflect"
)
func main() {
r := Rectangle{length:5, width:10}
printArea(&r)
s := Square{length:5, width:5}
printArea(&s)
}
type Shape interface {
area() int
}
type Rectangle struct {
length int
width int
}
type Square struct{
length int
width int
}
func (rect *Rectangle) area() int{
return rect.length * rect.width
}
func (square *Square) area() int{
return square.length * square.width
}
func printArea(shape Shape){
fmt.Printf("Area of %s is %d \n", reflect.TypeOf(shape) , shape.area())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment