Created
October 31, 2021 06:49
-
-
Save pkbhowmick/dd0c4ff16fa7a38f2f6fca9c35dc61eb to your computer and use it in GitHub Desktop.
An example of interface 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
// A simple example of interface in Golang: | |
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
type Shape interface { | |
GetArea() float64 | |
} | |
type Rectangle struct { | |
Length float64 | |
Height float64 | |
} | |
func NewRectangle(l, h float64) *Rectangle { | |
return &Rectangle{ | |
Length: l, | |
Height: h, | |
} | |
} | |
func (r *Rectangle) GetArea() float64 { | |
return r.Height * r.Length | |
} | |
type Circle struct { | |
Radius float64 | |
} | |
func NewCircle(r float64) *Circle { | |
return &Circle{ | |
Radius: r, | |
} | |
} | |
func (c *Circle) GetArea() float64 { | |
return c.Radius * c.Radius * math.Pi | |
} | |
var _ Shape = &Rectangle{} | |
var _ Shape = &Circle{} | |
func main() { | |
rec := NewRectangle(10, 6) | |
crl := NewCircle(2.5) | |
shapes := []Shape{rec, crl} | |
for _, o := range shapes { | |
fmt.Printf("Interface value: %v and type: %T\n", o, o) | |
fmt.Println(o.GetArea()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: