Last active
August 22, 2022 08:26
-
-
Save lantrix/b07b71844e5e7135e7b4e78224267edb to your computer and use it in GitHub Desktop.
How to use interfaces in golang from https://www.youtube.com/watch?v=lh_Uv2imp14
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" | |
type Box struct { | |
name string | |
colors []int | |
age int | |
} | |
func (b Box) getAge() int { | |
return b.age | |
} | |
func (b *Box) setAge(age int) { | |
b.age = age | |
} | |
func (b Box) getAvColors() float32 { | |
sum := 0 | |
for _, v := range b.colors { | |
sum += v | |
} | |
return float32(sum) / float32(len(b.colors)) | |
} | |
func (b Box) getMaxColour() int { | |
curMax := 0 | |
for _, v := range b.colors { | |
if curMax < v { | |
curMax = v | |
} | |
} | |
return curMax | |
} | |
func main() { | |
b1 := Box{"my box", []int{6, 7, 50}, 6} | |
b2 := Box{"my box", []int{78, 7, 50}, 6} | |
fmt.Println(b1.getAge()) | |
b1.setAge(9) | |
fmt.Println(b1.getAge()) | |
fmt.Println(b1.getAvColors()) | |
fmt.Println(b2.getAvColors()) | |
fmt.Println(b2.getMaxColour()) | |
} |
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" | |
"math" | |
) | |
type shape interface { | |
area() float64 | |
} | |
type circle struct { | |
radius float64 | |
} | |
type rect struct { | |
width float64 | |
height float64 | |
} | |
func (r *rect) area() float64 { | |
return r.width * r.height | |
} | |
func (c circle) area() float64 { | |
return math.Pi * c.radius * c.radius | |
} | |
func getArea(s shape) float64 { | |
return s.area() | |
} | |
func main() { | |
c1 := circle{4.5} | |
r1 := rect{5, 7} | |
shapes := []shape{c1, &r1} | |
for _, shape := range shapes { | |
fmt.Println(getArea(shape)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment