Created
October 29, 2019 01:19
-
-
Save donvito/e5676000976caa3d613df13cd7df76cf to your computer and use it in GitHub Desktop.
Go Interface example - print area of shapes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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