kdocs
GitHub
Lang - Runtime
Lang - Runtime
  • Go
    • Modules & Packages
    • Variables
    • Structs
    • Interfaces
    • Functions
    • Control Structures
    • Erro Handling
    • Concurrency
    • Testing
    • Fuzzing
  • Web
    • V8 Engine
    • Node.js
      • New Project
    • Deno
      • New Project
Powered by GitBook
On this page
  • Packages
  • Importing own packages
  • Add packages locally
  • Install packages
  • Modules
  1. Go

Modules & Packages

PreviousGoNextVariables

Last updated 1 month ago

Packages

Every Go application needs at least one package, that you can split your code in.

Usually you will have a default package main. Theoretically it could be any package name, as long as all files belong to the same package.

main is a special name for Go that tells it that this package will be the main entrypoint of the application.

  • In developing environments when executing the application with go run app.go you specify which file will be the entrypoint.

  • But for production environments, where the code is compiled to be runned, everything will be mixed together in the binary file, so the entrypoint from the package name is important.

Compiling a project without a main package produces no executable file.

You may also split your code into multiple packages.

Importing own packages

// Your own packages
import "your-module/package-name"

// Third-party that were downloaded with `go get`
import "https://package-url.com"

Variables, constants, functions, etc, are ONLY available (exported) to other packages if they start in Uppercase.

Ex.:

  • GetSomething(): this function will be available in other packages.

  • getSomething(): this function is "private" to the package that it is declared.

Add packages locally

This downloads the package and stores globally on your system.

go get https://package-url.com

Install packages

Just like npm install run bellow to install the projects dependencies.

It fetches the current required version (defined in your go.mod or latest compatible)

It not listed uet, it adds the latest matching your current module's Go version and requirements.

It does not update transitive dependencies unless needed.

It fetches a version that works with the rest of your dependencies. No wild upgrades.

go get

Fetches the latest available version of that package and all its dependencies (upgrades them!)

Can cause major upgrades to transitive deps.

Will pull the latest package AND the latest of all its nested imports (could affect other parts of your codebase)

go get -u

Modules

A module consist of multiple packages, and it is the go.mod file in your project.

Initiate the module in your project, or else, you will not be able to compile your project.

go mod init <path>

The path can be a name or dummy URL, or even a github repository URL.

Drawing
Drawing