Created
November 1, 2022 08:13
-
-
Save santosh/1fd57fa8693fcc177392e7204cd40beb to your computer and use it in GitHub Desktop.
Interface as value.
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
package main | |
import ( | |
"fmt" | |
) | |
type Animal interface { | |
Speak() string | |
} | |
type Dog struct { | |
} | |
func (d Dog) Speak() string { | |
return "Woof!" | |
} | |
type Cat struct { | |
} | |
func (d *Cat) Speak() string { | |
return "Meow!" | |
} | |
type Llama struct { | |
} | |
func (d Llama) Speak() string { | |
return "??????" | |
} | |
type JavaProgrammer struct { | |
} | |
func (d JavaProgrammer) Speak() string { | |
return "Design patterns!" | |
} | |
func main() { | |
animals := []Animal{&Dog{}, &Cat{}, Llama{}, JavaProgrammer{}} | |
for _, animal := range animals { | |
fmt.Println(animal.Speak()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment