Home > Articles > Programming

A Go Primer

  • Print
  • + Share This
This chapter is from the book

Declaring Structures

From: struct.go

4 type Example struct {
5   Val string
6   count int
7 }

Structures in Go are somewhat richer than C structures. One of the most important differences is that Go structures automatically support data hiding.

Any top-level type, method, or variable name that starts with a capital letter is visible outside of the package in which it is declared. This extends to structure fields. In C, if you only put some fields from a structure in a header, then you will encounter problems when someone tries to allocate an instance of it on the stack: his compiler won’t allocate enough space for it. Go packages export the offsets of the public fields. This allows them to be created and their public fields accessed from other compilation units.

The example at the start of this section defines a structure with two fields. The first, a string, is public and can be accessed from anywhere. The second, an integer, is private and is only visible to code in the same package as this definition. A structure doesn’t have to declare any public fields. You can create opaque types by defining a structure where all of the fields are private.

If you’re coming from a class-based language like C++ or Java, then you may be wondering why there are public and private fields, but not protected ones. The answer is quite simple: there is no inheritance in Go, so protected would have no meaning. Public and private also have slightly different meanings in Go and a language like Java. A private field in a Go structure can be accessed by any code in the same package, not just by methods of that structure. If you come from Objective-C, then you can think of private fields in Go structures like @package instance variables in Objective-C. If you come from C++, then think of all Go functions in a package as implicitly being friends of all structures declared in the same package.

  • + Share This
  • 🔖 Save To Your Account