Concept Flow - Practical use cases
Start Program
Define Function
Call Function
Process Data
Output Result
End Program
This flow shows how a Go program runs practical tasks: define functions, call them, process data, and output results.
package main import "fmt" func main() { nums := []int{1,2,3,4} sum := sumSlice(nums) fmt.Println(sum) } func sumSlice(s []int) int { total := 0 for _, v := range s { total += v } return total }
| Step | Action | Variable Values | Output |
|---|---|---|---|
| 1 | Start main function | nums=[1 2 3 4], sum=undefined | |
| 2 | Call sumSlice with nums | s=[1 2 3 4], total=0 | |
| 3 | Loop iteration 1 | v=1, total=0+1=1 | |
| 4 | Loop iteration 2 | v=2, total=1+2=3 | |
| 5 | Loop iteration 3 | v=3, total=3+3=6 | |
| 6 | Loop iteration 4 | v=4, total=6+4=10 | |
| 7 | Return total=10 to main | sum=10 | |
| 8 | Print sum | sum=10 | 10 |
| 9 | End program |
| Variable | Start | After 1 | After 2 | After 3 | After 4 | Final |
|---|---|---|---|---|---|---|
| total | 0 | 1 | 3 | 6 | 10 | 10 |
| v | undefined | 1 | 2 | 3 | 4 | 4 |
| sum | undefined | undefined | undefined | undefined | undefined | 10 |
Go practical use case: define functions to process data. Use slices to hold collections. Loop over slices with for-range. Accumulate results in variables. Return results and print output. Simple, clear steps for real tasks.
net/http package provides tools to create web servers in Go.http.ListenAndServe starts a server listening on a specified port.net/http package with http.ListenAndServe -> Option Anet/http.ListenAndServe [OK]os.Open opens a file in read-only mode and returns a file and error.file, err := os.Open("data.txt") correctly assigns both file and error.package main
import "fmt"
func main() {
nums := []int{2, 4, 6}
squares := make(map[int]int)
for _, n := range nums {
squares[n] = n * n
}
fmt.Println(squares)
}package main
import (
"fmt"
"os"
)
func main() {
file := os.Open("file.txt")
defer file.Close()
fmt.Println("File opened")
}os.Open returns two values: file and error. The code only assigns one variable.os.Open opens the file for reading; then you can scan or read lines.os.Create to create output file and WriteString or similar to write results.os.Open to read, loop to square, and os.Create with WriteString to save -> Option DPass the test and this pattern moves unknown