Skip to content

Instantly share code, notes, and snippets.

@azhuox

azhuox/block3.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/7cfdf4fae175818efd926db25cda10fb to your computer and use it in GitHub Desktop.
Save azhuox/7cfdf4fae175818efd926db25cda10fb to your computer and use it in GitHub Desktop.
package encapsulationexample
import "fmt"
// CounterDemo shows how to directly access "private" fields of `Counter` struct in the same package.
func CounterDemo() {
c := NewCounter()
// I can directly access the `counter` field!
c.counter = 5
// It will print out "counter value: 5".
fmt.Print("counter value: %d\n", c.N())
}
package otherpackage
import "fmt"
// CounterDemo shows "private" fields of `Counter` struct cannot be directly accessed by another package.
func CounterDemo2() {
c := NewCounter()
// This would cause a compiler error as the private field `counter` is not visible in this package.
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