clarkk
clarkk

Reputation: 27689

private/public fields in structs.. acting differently

Why can I do this

package main

import "fmt"

func main() {
    c := Circle{x: 0, y: 0, r: 5}
    fmt.Println(c.r)
}

type Circle struct {
    x float64
    y float64
    r float64
}

http://play.golang.org/p/0ypcekVDV9

When I can't do the same with a struct in a package?

If I would try to access a struct with a field with lowercase a compiler error is returned..

Upvotes: 1

Views: 1746

Answers (2)

IamNaN
IamNaN

Reputation: 6864

As already stated, the fields need to be exported to be accessible from another package. See the spec

Exported identifiers

An identifier may be exported to permit access to it from another package. An identifier is exported if both:

  • the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu");
  • and the identifier is declared in the package block or it is a field name or method name. All other identifiers are not exported.

If you want to keep the fields private, you need to use accessor (set/get) methods which you can read about here

Getters

Go doesn't provide automatic support for getters and setters. There's nothing wrong with providing getters and setters yourself, and it's often appropriate to do so, but it's neither idiomatic nor necessary to put Get into the getter's name. If you have a field called owner (lower case, unexported), the getter method should be called Owner (upper case, exported), not GetOwner. The use of upper-case names for export provides the hook to discriminate the field from the method. A setter function, if needed, will likely be called SetOwner. Both names read well in practice:

owner := obj.Owner()
if owner != user {
    obj.SetOwner(user)
}

Upvotes: 5

Jean Hominal
Jean Hominal

Reputation: 16796

If the struct is in a different package than the main function, then you cannot access the struct's private fields from that main function.

That is what "private" means.

Upvotes: 3

Related Questions