Golang packages: Difference between revisions

From wikinotes
No edit summary
Line 109: Line 109:
</blockquote><!-- init function -->
</blockquote><!-- init function -->
</blockquote><!-- Defining Packages -->
</blockquote><!-- Defining Packages -->
= Internal Packages =
<blockquote>
Packages defined within the <code>internal/</code> directory can export symbols for internal use, but it will not be publicly available outside of the module.
<syntaxhighlight lang="bash">
mygolib/
  internal/
    someInternalPackage/
    someOtherInternalPackage/
    ...
  go.mod
</syntaxhighlight>
</blockquote><!-- Internal Packages -->

Revision as of 15:37, 6 June 2022

Basics

  • Packages are groups of related code.
  • Exported functions are callable when a package is imported
  • The main package is your program's entrypoint (ex. cli)

Imports

import "fmt"

import (
    "fmt"                                // builtin pkgs have no module-path prefix
    "golang.org/x/example/stringutil"    // non-builtin pkgs have module-path prefix (incl. local sub-packages)
)

Defining Packages

Anatomy

# project heirarchy
myproject/
    mypackage/
        libfoo.go
        libbar.go
    main.go
    go.mod

myproject/go.mod

// go.mod

module github.com/you/myproject

go 1.18

myproject/main.go

// main.go

package main

import "github.com/you/myproject/mypackage"

func main() {
    mypackage.PrintHi();
}

myproject/mypackage/libfoo.go

// mypackage/libfoo.go

package mypackage

import "fmt"

func PrintHi() {
    fmt.Println("hi")
}

Exported Functions

TODO:

Needs much more detail, and confirmation. (ex. what about constants? classes?)

Only exported symbols are exposed when a package is imported.

  • Exported symbols/variables are upper-cased.

init function

Each file within a package can define an init function.
This function is evaluated the first time the package is imported.

// names/name.go

import "fmt"

package names

var name string

func init() {
    name = "foo"
    fmt.Println("imported the first time")
}

Internal Packages

Packages defined within the internal/ directory can export symbols for internal use, but it will not be publicly available outside of the module.

mygolib/
  internal/
    someInternalPackage/
    someOtherInternalPackage/
    ...
  go.mod