Packages, variables, and functions


HelloWorld


package main

import "fmt"

func main() {
	fmt.Println("hello world")
}

Importing Package


import (
	"fmt"
	"math/rand"
	"time"
)

// or

import "fmt"
import "math/rand"

<aside> ☝️ In Go, a name is exported if it begins with a capital letter. For example, Pizza is an exported name, as is Pi, which is exported from the math package.

</aside>

import (
	// built-in packages, alphabetical order
	"fmt"
	"http"
	
	// local packages, alphabetical order
	"github.com/justin0u0/example/foo/bar"
	"github.com/justin0u0/example/foo/baz"

	// third-party packages, alphabetical order
	"github.com/google/uuid"
	"go.uber.org/zap"
)

<aside> ☝ In golang, we often group import packages by built-in, local and third-party and sort each group by alphabetical order. If using VSCode, the order will be automatically sorted.

</aside>

import (
	_ "github.com/justin0u0/example/foo/bar"
)

<aside> ☝ An unused import, can be used to initialize if the package has init() function.

</aside>

Function


Basic

func add(x int, y int) int {
	return x + y
}

// or 

func add(x, y int) int {
	return x + y
}

Multiple result

func swap(x, y int) (int, int) {
	return y, x
}