This file contains 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 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