Last active
October 3, 2021 09:29
-
-
Save mkock/220e8f4ff545eb7be8e4e55dace36fa2 to your computer and use it in GitHub Desktop.
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
| type monster struct { | |
| damage int | |
| } | |
| func (m *monster) attack() int { | |
| return m.damage | |
| } | |
| type attacker interface { | |
| attack() int | |
| } | |
| type defender interface { | |
| defend() int | |
| } | |
| func attackOrDefend(attackerDefender interface{}) { | |
| // Inside this function, we don't know what we're getting, but we can check! | |
| if attacker, ok := attackerDefender.(attacker); ok { | |
| fmt.Printf("Attacking with damage %d\n", attacker.attack()) | |
| } else if defender, ok := attackerDefender.(defender); ok { | |
| fmt.Printf("Defending with damage %d\n", defender.defend()) | |
| } | |
| } | |
| func main() { | |
| var a attacker = &monster{200} | |
| attackOrDefend(a) // Prints "Attacking with damage 200" | |
| attackOrDefend("Hello") // This is allowed, but does nothing. | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment