Skip to content

Instantly share code, notes, and snippets.

@neilchaudhuri
Created March 21, 2019 02:10
Show Gist options
  • Save neilchaudhuri/1b5c2024980149bf58ebed603b6f578d to your computer and use it in GitHub Desktop.
Save neilchaudhuri/1b5c2024980149bf58ebed603b6f578d to your computer and use it in GitHub Desktop.
Example of idiomatic Go polymorphism
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