Module 2: Go Basics
Detailed Topics:
Syntax and Constructs
Go offers a straightforward syntax that emphasizes readability. Key elements include:
Variable Declaration:
Declare variables using
var
or shorthand:=
.
var x int = 10 y := 20Constants:
Use
const
to define immutable values.
const Pi = 3.14Functions:
Define reusable code blocks.
func add(a int, b int) int { return a + b }
Data Types and Collections
Slices:
Dynamic arrays that adjust size as needed.
numbers := []int{1, 2, 3, 4} numbers = append(numbers, 5)Maps:
Key-value data structures for fast lookups.
scores := map[string]int{"Alice": 90, "Bob": 85} fmt.Println(scores["Alice"])
Control Structures
Conditional Statements:
if x > 0 { fmt.Println("Positive") } else { fmt.Println("Non-positive") }For-Loops:
for i := 0; i < 5; i++ { fmt.Println(i) }Switch Cases:
switch day := "Monday"; day { case "Monday": fmt.Println("Start of the week") default: fmt.Println("Another day") }
Detailed Hands-On
Practice Slicing Arrays and Iterating Over Maps
Slice Manipulation:
fruits := []string{"apple", "banana", "cherry"} fmt.Println(fruits[1:])Map Iteration:
capitals := map[string]string{"France": "Paris", "Italy": "Rome"} for country, capital := range capitals { fmt.Printf("%s: %s\n", country, capital) }
Create a Recursive and Iterative Function to Compute Factorials
Recursive Factorial:
func factorialRecursive(n int) int { if n == 0 { return 1 } return n * factorialRecursive(n-1) }Iterative Factorial:
func factorialIterative(n int) int { result := 1 for i := 1; i <= n; i++ { result *= i } return result }
Last modified: 18 December 2024