Created
February 3, 2021 17:14
-
-
Save anshajk/405b0455ccd43ffddc72370e410fd224 to your computer and use it in GitHub Desktop.
Interface example in golang
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
//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