I understand from the Go tour that upper case variables are meant to be exported, while lower case variables in a struct are not exported. But I am trying to achieve something else.
In Java, I could define a class Adult
, like so
class Adult
{
private int age;
void setAge(int x)
{
if (x >= 18)
this.age = x;
}
}
In GoLang, I understand I could do something similar like so:
//adult.go
package main
type Adult struct {
age int //Made this lowercase, therefore private. I expect no one messes with this.
}
func (a *Adult) setAge(x int) { //Setter only
if x >= 18 {
a.age = x
}
}
However, I can do this in my main.go
:
package main
import "fmt"
func (a *Adult) getAge() *int { // This shouldn't be possible?
return &a.age
}
func main() {
var temp *Adult = new(Adult)
temp.setAge(24)
fmt.Println(*temp.getAge())
var this_age_should_be_hidden = temp.getAge() //How do I prevent someone from doing this?
*this_age_should_be_hidden = 5
fmt.Println(*temp.getAge())
}
That brings me to the title of this question. If we lower case our variables, what is the point? Can we always define methods on the struct which would expose unexported variables? Doesn't that defeat the purpose of lowercasing it, in the first place?
Also, what would be the Go way to achieve what I have done in the Java version above? How can I ensure that certain fields of my structs are not set to invalid values outside the class?