IntroductionOne of the first things I learned about in Go was using an uppercase or lowercase letter as the first letter when naming a type, variable or function. It was explained that when the first letter was capitalized, the identifier was public to any piece of code that wanted to use it. When the first letter was lowercase, the identifier was private and could only be accessed within the package it was declared.NEXT Level Go & DevOps TrainingLearn More
I have come to realize that the use of the language public and private is really not accurate. It is more accurate to say an identifier is exported or unexported from a package. When an identifier is exported from a package, it means the identifier can be directly accessed from any other package in the code base. When an identifier is unexported from a package, it can’t be directly accessed from any other package. What we will soon learn is that just because an identifier is unexported, it doesn’t mean it can’t be accessed outside of its package, it just means it can’t be accessed directly.Direct Identifier AccessLet’s start with a simple example of an exported type:AlertCounter inside the package counters. This type is an alias for the built-in type int, but in Go AlertCounter will be considered a unique and distinct type. We are using the capital letter ‘A’ as the first letter for the name of the type, which means this type is exported and accessible by other packages.Now let’s access our AlertCounter type in the main program:AlertCounter type has been exported, this code builds fine. When we run the program we get the value of 10.Now let’s change the exported AlertCounter type to be an unexported type by changing the name to alertCounter and see what happens:counters and main packages, we attempt to build the code again and get the following compiler error:
Get your team up to date with best practices & customized curriculum.
We help you evaluate your architecture, design, structure, tech-debt and human capital.
Learn at your own pace!
Special offers on upcoming training events & our latest blog posts.
Valid email required.
Submit failed. Try again or message us directly at email@example.com.
Check your email for confirmation.
We've built our reputation as educators and bring that mentality to every project. When you partner with us, your team will learn best practices and grow along the way.
Years in Business
Please fill out the form below, and we'll get back to you soon.
Check your email for confirmation of your sent message. We'll get back to you shortly.
Ardan Labs Copyrights © 2023