Go Learning Material
This document provides an introduction to Go (Golang), a modern, open-source
programming language designed for simplicity, performance, and concurrency.
It covers the basics of Go, including installation, syntax, data types, functions,
and concurrency, with practical examples.
Table of Contents
1. What is Go?
2. Installing Go
3. Basic Syntax and Structure
4. Data Types and Variables
5. Functions
6. Concurrency with Goroutines and Channels
7. Common Go Commands
8. Practice Exercises
What is Go?
Go is a statically typed, compiled programming language developed by Google. It
is known for its simplicity, fast compilation, and built-in support for concurrency,
making it ideal for building scalable, high-performance applications.
Installing Go
To get started with Go:
1. Download Go: Visit [Link] and download the installer for your operating
system.
2. Install Go: Follow the installation instructions for your platform (Win-
dows, macOS, or Linux).
3. Verify Installation: Open a terminal and run:
go version
This should display the installed Go version, e.g., go1.21.0.
4. Set Up Workspace: Create a directory for your Go projects (e.g., ~/go) and
set the GOPATH environment variable if needed (not required for Go modules).
Basic Syntax and Structure
A basic Go program has the following structure:
package main
import "fmt"
func main() {
1
[Link]("Hello, Go!")
}
• package main: Declares the package name. main is the entry point for
executable programs.
• import "fmt": Imports the fmt package for formatting and printing.
• func main(): The main function where execution starts.
• [Link]: Prints text to the console.
Save this as [Link] and run it:
go run [Link]
Data Types and Variables
Go is statically typed, and variables are declared with explicit types or inferred
using the := operator.
Basic Data Types
• Integers: int, int32, int64, etc.
• Floating-point: float32, float64.
• Strings: string, e.g., "hello".
• Booleans: bool, e.g., true or false.
Variable Declaration
package main
import "fmt"
func main() {
var x int = 10 // Explicit type
y := 20 // Type inference
name := "Alice" // String
isActive := true // Boolean
[Link]("x: %d, y: %d, name: %s, isActive: %t\n", x, y, name,
isActive)
}
Arrays and Slices
• Array: Fixed-length collection of elements.
• Slice: Dynamic, flexible view of an array.
numbers := []int{1, 2, 3, 4, 5} // Slice
numbers = append(numbers, 6) // Add element to slice
[Link](numbers) // Output: [1 2 3 4 5 6]
2
Functions
Functions in Go are declared using the func keyword. They can return multiple
values.
Example: Calculate Sum and Average
package main
import "fmt"
func sumAndAverage(numbers []int) (int, float64) {
sum := 0
for _, num := range numbers {
sum += num
}
avg := float64(sum) / float64(len(numbers))
return sum, avg
}
func main() {
nums := []int{10, 20, 30, 40}
total, average := sumAndAverage(nums)
[Link]("Sum: %d, Average: %.2f\n", total, average)
}
Concurrency with Goroutines and Channels
Go’s concurrency model uses goroutines (lightweight threads) and channels for
communication.
Example: Goroutines
package main
import (
"fmt"
"time"
)
func printMessage(msg string) {
for i := 0; i < 3; i++ {
[Link](msg, i)
[Link](100 * [Link])
}
}
func main() {
go printMessage("Goroutine 1") // Run concurrently
go printMessage("Goroutine 2")
[Link](1 * [Link]) // Wait for goroutines to finish
}
3
Example: Channels
package main
import "fmt"
func sendNumbers(ch chan int) {
for i := 1; i <= 3; i++ {
ch <- i // Send to channel
}
close(ch)
}
func main() {
ch := make(chan int)
go sendNumbers(ch)
for num := range ch { // Receive from channel
[Link]("Received:", num)
}
}
Common Go Commands
• go run <[Link]>: Runs a Go program.
• go build: Compiles a Go program into an executable.
• go mod init <module-name>: Initializes a Go module.
• go get <package>: Downloads and installs a package.
• go fmt: Formats Go source code.
• go test: Runs tests in the project.
Practice Exercises
1. Write a program to calculate the square of a number using a function.
2. Create a slice of student names and print them in reverse order.
3. Write a function that takes a slice of integers and returns the minimum
and maximum values.
4. Create a goroutine that prints even numbers from 1 to 10.
5. Use a channel to send and receive the first 5 Fibonacci numbers.
Example Solutions
Exercise 1: Square Function package main
import "fmt"
func square(num int) int {
return num * num
}
func main() {
[Link]("Square of 5:", square(5)) // Output: Square of 5: 25
}
4
Exercise 2: Reverse Slice package main
import "fmt"
func main() {
students := []string{"Alice", "Bob", "Charlie"}
for i := len(students) - 1; i >= 0; i-- {
[Link](students[i])
}
}
Exercise 3: Min and Max package main
import "fmt"
func minMax(numbers []int) (int, int) {
min, max := numbers[0], numbers[0]
for _, num := range numbers {
if num < min {
min = num
}
if num > max {
max = num
}
}
return min, max
}
func main() {
nums := []int{3, 1, 4, 1, 5, 9}
min, max := minMax(nums)
[Link]("Min: %d, Max: %d\n", min, max)
}
Exercise 4: Goroutine for Even Numbers package main
import (
"fmt"
"time"
)
func printEvens() {
for i := 1; i <= 10; i++ {
if i%2 == 0 {
[Link](i)
}
}
}
func main() {
go printEvens()
[Link](1 * [Link])
}
5
Exercise 5: Fibonacci with Channels package main
import "fmt"
func fibonacci(ch chan int, n int) {
a, b := 0, 1
for i := 0; i < n; i++ {
ch <- a
a, b = b, a+b
}
close(ch)
}
func main() {
ch := make(chan int)
go fibonacci(ch, 5)
for num := range ch {
[Link]("Fibonacci:", num)
}
}
Conclusion
This material provides a foundation for learning Go. Practice these exam-
ples in a Go environment (e.g., Go Playground or local setup) to build profi-
ciency. For advanced topics, explore packages like net/http for web develop-
ment, encoding/json for JSON handling, and testing for unit tests.