Skip to content

Instantly share code, notes, and snippets.

@azhuox

azhuox/block4.go Secret

Created December 2, 2020 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azhuox/48d03a95c53ca164c47ac8a1eb8d710e to your computer and use it in GitHub Desktop.
Save azhuox/48d03a95c53ca164c47ac8a1eb8d710e to your computer and use it in GitHub Desktop.
package encapsulationexample
// Counter defines the interface that a counter instance needs to implement.
type Counter interface{
N() int
Increment()
Reset()
}
// SimpleCounter - a simple counter.
type simpleCounter struct {
counter int
}
func NewSimpleCounter() Counter {
return &simpleCounter{
counter: 0,
}
}
func (c *simpleCounter) N() int { return c.counter }
func (c *simpleCounter) Increment() { c.counter++ }
func (c *simpleCounter) Reset() { c.counter = 0 }
// CounterDemo shows how to use the `Counter` interface.
func CounterDemo() {
var c Counter
c = NewSimpleCounter()
// This would cause a compiler error as the `Counter` interface does not have `counter` field.
c.counter = 5
// It will print out "counter value: 0" if you comment the above statement.
fmt.Print("counter value: %d\n", c.N())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment