Skip to content

Instantly share code, notes, and snippets.

@proudlygeek
Created April 28, 2014 10:46
Show Gist options
  • Select an option

  • Save proudlygeek/11368185 to your computer and use it in GitHub Desktop.

Select an option

Save proudlygeek/11368185 to your computer and use it in GitHub Desktop.
Opaque interfaces in Golang
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
}
// 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())
}
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