Go Language Essentials: Core Concepts

Go programs are organized into packages. Execution always begins in the main package. This program imports the fmt package for formatting I/O and math/rand for random number generation.

By convention, a package's name typically matches its import path's last element. For example, "math/rand" contains source files that begin with the statement package rand.

package main

import (
	"fmt"
	"math/rand"
)

func main() {
	// In a typical Go playground environment, math/rand produces
	// the same sequence of numbers on each run because the seed is fixed.
	// For truly random outcomes in a real application, a unique seed
	// (e.g., based on current time) must be supplied using rand.Seed().
	fmt.Println("A random digit between 0 and 9 is:", rand.Intn(10))
}

Imports

Go supports both grouped and individual import statements. Grouping imports into a single parenthesized block is generally preferred for clarity and conciseness.

package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Printf("The square root of 64 is approximately %g.\n", math.Sqrt(64))
}

Alternatively, multiple single import statements can be written:

import "fmt"
import "math"

Exported Names

In Go, identifiers (like variables, functions, types) starting with an uppercase letter are 'exported' or publicly visible outside their package. Conversely, identifiers beginning with a lowercase letter are unexported and remain private to their package.

For instance, User and Compute are exported names. math.Pi is an exported constant from the math package. Names like user or compute are unexported.

When importing a package, you can only reference its exported names. Any unexported identifiers are inaccessible from out side that package.

Functions

Functions can accept zero or more arguments and return any number of results. For consecutive parameters of the same type, the type declaration can be omitted for all but the last parameter.

// Both parameters explicitly typed
func calculateSum(val1 int, val2 int) int {
	return val1 + val2
}

// Concise syntax: type omitted for val1 as it matches val2's type
func calculateSumConcise(val1, val2 int) int {
	return val1 + val2
}

Functions can also return multiple results.

// This function swaps two string arguments and returns them in reverse order.
func reverseStrings(first, second string) (string, string) {
	return second, first
}

Go's return values can be named, treating them as variables declared at the top of the function. Named return values enhance code readability by serving as documentation.

A return statement without arguments returns the current values of the named return variables. This is known as a

Tags: Go Golang programming fundamentals Basics

Posted on Wed, 04 Nov 2026 16:11:20 +0000 by wardmaestro