Last active
January 13, 2019 18:52
-
-
Save prakashpandey/1d7f6aedc20daad1207ec4cd1e3b1321 to your computer and use it in GitHub Desktop.
How to implement multiple interfaces in golang?
This file contains hidden or 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
// | |
// Author: github.com/prakashpandey | |
// | |
// How interfaces works in golang using? | |
// | |
// In this sample program, our type 'Rectangle' will implement two interfaces | |
// - Type 'Rectangle' implements two interfaces: | |
// 1. Geometry | |
// 2. Color | |
// - To implement interfaces in golang, we don't have to do anything special, | |
// just make sure that the type have all the methods defined in the interface signature | |
// | |
package main | |
import ( | |
"fmt" | |
) | |
// Geometry interface | |
type Geometry interface { | |
area() float32 | |
parameter() float32 | |
numOfSides() int | |
} | |
// Color interface | |
type Color interface { | |
getColor() string | |
} | |
// Rectangle struct implements Geometry and Color interface | |
type Rectangle struct { | |
length, breadth float32 | |
color string | |
} | |
func (r Rectangle) area() float32 { | |
return r.length * r.breadth | |
} | |
func (r Rectangle) parameter() float32 { | |
return 2 * (r.length + r.breadth) | |
} | |
func (r Rectangle) numOfSides() int { | |
return 4 | |
} | |
func (r Rectangle) getColor() string { | |
return r.color | |
} | |
func area(g Geometry) float32 { | |
return g.area() | |
} | |
func getColor(c Color) string { | |
return c.getColor() | |
} | |
func main() { | |
r := Rectangle{ | |
length: 10, | |
breadth: 10, | |
color: "Red", | |
} | |
fmt.Printf("Area: %f \n", area(r)) | |
fmt.Printf("Color: %s \n", r.getColor()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment