Created
April 28, 2014 10:46
-
-
Save proudlygeek/11368185 to your computer and use it in GitHub Desktop.
Opaque interfaces in Golang
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
| package opaque | |
| type internalBasicType int | |
| // | |
| // Prevents the interface to be implemented | |
| // *outside* the package, since is lowerCase (thus private). | |
| // | |
| // This is best suited for API and things we don't | |
| // wanna people to override. | |
| // | |
| func (m *internalBasicType) implementsOpaque() {} | |
| func (m *internalBasicType) GetNumber() int { | |
| return int(*m) | |
| } | |
| func NewBasic(number int) Opaque { | |
| // This is a pointer to an int | |
| o := internalBasicType(number) | |
| // Derefence the pointer | |
| return &o | |
| } |
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
| // http://www.onebigfluke.com/2014/04/gos-power-is-in-emergent-behavior.html?utm_content=buffer5ee21&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer | |
| package opaque | |
| import "fmt" | |
| type Opaque interface { // Public | |
| GetNumber() int // Public | |
| implementsOpaque() // Private | |
| } | |
| func DoSomethingWithOpaque(o Opaque) string { | |
| return fmt.Sprintf("Hello opaque #%d", o.GetNumber()) | |
| } |
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
| package main | |
| import ( | |
| "fmt" | |
| "opaque" | |
| ) | |
| func main() { | |
| o := opaque.NewBasic(15) | |
| s := opaque.DoSomethingWithOpaque(o) | |
| fmt.Println("Doing something with an opaque i get:", s) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment