Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Working with Packages | Packages, Modules, and Generics
/
Advanced Go

bookWorking with Packages

Desliza para mostrar el menú

You will explore how to structure and organize code using packages in Go. You will learn about visibility rules that determine which functions, types, and variables can be accessed from outside a package.

Visibility in Go Packages

Go uses a simple rule to control visibility of identifiers (such as variables, functions, types, and constants) within packages:

  • Exported identifiers: Start with an uppercase letter; can be accessed from other packages;
  • Unexported identifiers: Start with a lowercase letter; are private to the current package.

This rule applies to any identifier you define. For example, PrintMessage would be accessible from outside its package, while formatMessage would be hidden from other packages.

Example:

// In package greetings
type Person struct { // exported, accessible from other packages
    Name string
}

func SayHello() { // exported
    // ...
}

func formatGreeting(name string) string { // unexported, only for use inside 'greetings' package
    // ...
}

When using another package, you can only access its exported identifiers. Unexported identifiers are invisible to code outside their package, which helps you control your package’s public API and prevent unwanted access to internal details.

Organizing Code Across Multiple Files in a Package

When your Go project grows, you often need to split code into several files for clarity and maintainability. In Go, you can organize related code into multiple files within the same package by following these rules:

  • Place all related files in the same directory;
  • Use the same package name at the top of each file;
  • Only one file in the directory should contain the main() function if it is an executable package.

By doing this, all files in the directory become part of the same package. This allows you to define functions, types, and variables in separate files, but access them as if they were in one file. For example, you might have math.go and util.go in a calculator package, both starting with package calculator. All exported functions and types are available throughout the package.

This approach keeps your code organized and makes it easier to maintain as your project grows.

question mark

Which statements correctly describe the difference between exported and unexported identifiers in Go packages

Select all correct answers

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 1

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 2. Capítulo 1
some-alt