Skip to content

Instantly share code, notes, and snippets.

@mkock
Last active October 3, 2021 09:20
Show Gist options
  • Select an option

  • Save mkock/0ebeb323c5c86e91dd488ef2cdd457c1 to your computer and use it in GitHub Desktop.

Select an option

Save mkock/0ebeb323c5c86e91dd488ef2cdd457c1 to your computer and use it in GitHub Desktop.
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