Skip to content

Instantly share code, notes, and snippets.

@anshajk
Created February 3, 2021 17:14
Show Gist options
  • Save anshajk/405b0455ccd43ffddc72370e410fd224 to your computer and use it in GitHub Desktop.
Save anshajk/405b0455ccd43ffddc72370e410fd224 to your computer and use it in GitHub Desktop.
Interface example in golang
//A very simple example of an interface in golang
package main
import "fmt"
type apple struct {
calories int
}
type orange struct {
calories int
}
type fruit interface {
getCalories() int
}
func main() {
fruitOne := apple{}
fruitTwo := orange{}
printCalories(fruitOne)
printCalories(fruitTwo)
}
func printCalories(f fruit) {
fmt.Println("Calories in fruit are:", f.getCalories())
}
func (o orange) getCalories() int {
return 200
}
func (a apple) getCalories() int {
return 100
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment