Created
March 21, 2019 02:10
-
-
Save neilchaudhuri/1b5c2024980149bf58ebed603b6f578d to your computer and use it in GitHub Desktop.
Example of idiomatic Go polymorphism
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
package main | |
import ( | |
"fmt" | |
) | |
type Named struct { | |
name string | |
} | |
type Connection struct { | |
Named | |
database string | |
} | |
type Closeable interface { | |
close() string | |
} | |
func (c Connection) close() string { | |
return fmt.Sprintf("Closing connection %v", c.name) | |
} | |
type File struct { | |
Named | |
opener string | |
} | |
func (f File) close() string { | |
return fmt.Sprintf("Closing %v", f.name) | |
} | |
func showClosing(c Closeable) string { | |
return c.close() | |
} | |
func main() { | |
connection := Connection{Named{name: "MyConnection"}, "PostgreSQL"} | |
file := File{Named{name: "file.txt"}, "TextEdit"} | |
fmt.Println(showClosing(connection)) | |
fmt.Println(showClosing(file)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment