What is Go?
Go (Golang) is a statically typed programming language created at Google.
Goals:
- Simple syntax
- Fast compilation
- Single executable deployment
- Garbage collection
- Built-in concurrency support
Commonly used for: - Backend services
- Cloud infrastructure
- DevOps tools
- Command-line applications
Examples of software written in Go: - Docker
- Kubernetes
- Terraform
- Prometheus
Structure of a Go Program
A minimal Go program:
package main
import "fmt"
func main() {
fmt.Println("Hello")
}package main
Marks the package as executable.
package mainPrograms start execution from the main() function inside package main.
import
Imports another package.
import "fmt"Similar concept to:
#include <stdio.h>or
import sysmain()
Entry point of the program.
func main() {
}Printing Output
fmt.Println("Hello")Prints a line followed by a newline.
Variables
Explicit Declaration
var version float64 = 0.1Type Inference
version := 0.1Go automatically infers the type.
Short declaration (:=) is commonly used when the value is known immediately.
Println and Automatic Spaces
Example:
fmt.Println("Version ", version)Output:
Version 0.1Reason:
- First argument already ends with a space.
Println()automatically inserts a space between arguments.
Preferred:
fmt.Println("Version", version)Reading User Input
var age int
fmt.Print("Enter age: ")
fmt.Scanln(&age)Why ’&’?
The & operator returns the address of a variable.
Scanln() needs a memory location where it can store the value entered by the user.
Similar to:
scanf("%d", &age);Command-Line Arguments
Import:
import "os"Arguments:
os.ArgsExample:
myprogram hello worldContents:
os.Args[0]Program name
os.Args[1]First argument
os.Args[2]Second argument
Basic Command Validation
if len(os.Args) < 2 {
fmt.Println("Usage: myprogram <command>")
return
}Check the first argument:
command := os.Args[1]Example:
if command == "hello" {
fmt.Println("Hello")
} else {
fmt.Println("Unknown command")
}Concepts Learned
Packages
package mainImports
import "fmt"
import "os"Functions
func main() {
}Variables
var name string
name := "Alice"Pointers (Basic Usage)
&variableUsed when another function needs access to the variable’s memory location.
User Input
fmt.Scanln()Command-Line Arguments
os.ArgsSession Summary
Topics covered:
- Structure of a Go program
- Packages
- Imports
- Functions
- Variables
- Type inference
- Console output
- Console input
- Pointers for input
- Command-line arguments
Practical result:
- Built and executed a Go application
- Accepted user input
- Processed command-line arguments
- Implemented simple command selection logic
Next Topics
- Functions
- Multiple source files
- Packages
- Structs
- Error handling
- Building larger command-line applications
- Go Learning - Session 3