Last active
October 3, 2021 09:20
-
-
Save mkock/0ebeb323c5c86e91dd488ef2cdd457c1 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 car struct {} | |
| func (c *car) start() { return } | |
| func (c *car) stop() { return } | |
| func (c *car) recycle() { fmt.Println("Recycling...") } | |
| type vehicle interface { | |
| start() | |
| stop() | |
| } | |
| type recyclable interface { | |
| recycle() | |
| } | |
| func main() { | |
| var v vehicle = new(car) | |
| if r, ok := v.(recyclable); ok { | |
| // In the scope of this code block, we've now asserted that v satisfies the recyclable interface. | |
| // Therefore, we can call recycle() on it! | |
| r.recycle() // Prints "Recycling..." | |
| } | |
| // v.recycle() // <- This is not possible! In the outer code block, we know that v is a vehicle, | |
| // but the assertion applies only to the code block containing r. Here, v is still just a vehicle. | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment