Ready to move from reading about Go to actually writing clean, idiomatic code with confidence? This post gives you 100 Go practice problems with clear, step-by-step solutions designed to make your skills truly stick. You’ll work through fundamentals like variables, slices, maps, and functions, then tackle structs, interfaces, goroutines, channels, and error handling. Each problem is explained in plain, simple language—try it yourself first, then check the solution and deeply understand the why behind the code.
Practice is everything because Go is a craft best learned by doing; every challenge you solve builds muscle memory and turns tricky concepts into natural habits. Whether you’re just starting out with Golang or preparing for a backend interview, these exercises will help you feel capable and genuinely ready. Pick a problem, start coding, and enjoy that “I really got this!” moment.
Also try it: 100 Rust practice problems with solutions
1. Write a program that prints “Hello, World!” to the console.
go
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
2. Write a program that declares two integer variables, assigns them values, and prints their sum.
go
package main
import "fmt"
func main() {
a, b := 10, 20
fmt.Println("Sum:", a+b)
}
3. Write a program that takes an integer input from the user and prints whether it is even or odd.
go
package main
import "fmt"
func main() {
var num int
fmt.Print("Enter a number: ")
fmt.Scan(&num)
if num%2 == 0 {
fmt.Println(num, "is even")
} else {
fmt.Println(num, "is odd")
}
}
4. Write a program that prints the numbers from 1 to 10 using a for loop.
go
package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
fmt.Print(i, " ")
}
}
5. Write a program that prints the factorial of a given number (e.g., 5).
go
package main
import "fmt"
func main() {
n := 5
fact := 1
for i := 1; i <= n; i++ {
fact *= i
}
fmt.Println("Factorial of", n, "is", fact)
}
6. Write a program to reverse a string (e.g., “Hello” → “olleH”).
go
package main
import "fmt"
func main() {
str := "Hello"
runes := []rune(str)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
fmt.Println(string(runes))
}
7. Write a program to check if a string is a palindrome (e.g., “radar”).
go
package main
import "fmt"
func isPalindrome(s string) bool {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
if runes[i] != runes[j] {
return false
}
}
return true
}
func main() {
str := "radar"
fmt.Println(str, "is palindrome?", isPalindrome(str))
}
8. Write a program to find the largest element in an array {3, 7, 1, 9, 4}.
go
package main
import "fmt"
func main() {
arr := [5]int{3, 7, 1, 9, 4}
max := arr[0]
for _, v := range arr {
if v > max {
max = v
}
}
fmt.Println("Largest:", max)
}
9. Write a program to calculate the sum of all elements in an array {2,4,6,8}.
go
package main
import "fmt"
func main() {
arr := []int{2, 4, 6, 8}
sum := 0
for _, v := range arr {
sum += v
}
fmt.Println("Sum:", sum)
}
10. Write a program that counts the number of vowels in a string “Hello World”.
go
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello World"
vowels := "aeiouAEIOU"
count := 0
for _, ch := range str {
if strings.ContainsRune(vowels, ch) {
count++
}
}
fmt.Println("Vowels:", count)
}
11. Write a program that prints the Fibonacci series up to 10 terms.
go
package main
import "fmt"
func main() {
n := 10
a, b := 0, 1
fmt.Print("Fibonacci: ")
for i := 0; i < n; i++ {
fmt.Print(a, " ")
a, b = b, a+b
}
}
12. Write a program that checks if a given number is prime (e.g., 17).
go
package main
import (
"fmt"
"math"
)
func isPrime(n int) bool {
if n <= 1 {
return false
}
for i := 2; i <= int(math.Sqrt(float64(n))); i++ {
if n%i == 0 {
return false
}
}
return true
}
func main() {
num := 17
fmt.Println(num, "is prime?", isPrime(num))
}
13. Write a program to remove duplicate elements from a slice {1,2,2,3,4,4,5}.
go
package main
import "fmt"
func main() {
slice := []int{1, 2, 2, 3, 4, 4, 5}
seen := make(map[int]bool)
result := []int{}
for _, v := range slice {
if !seen[v] {
seen[v] = true
result = append(result, v)
}
}
fmt.Println(result)
}
14. Write a program that sorts a slice {5,2,8,1,3} in ascending order.
go
package main
import (
"fmt"
"sort"
)
func main() {
slice := []int{5, 2, 8, 1, 3}
sort.Ints(slice)
fmt.Println(slice)
}
15. Write a program that finds the second largest number in a slice {10,20,4,45,99}.
go
package main
import (
"fmt"
"sort"
)
func main() {
slice := []int{10, 20, 4, 45, 99}
sort.Ints(slice)
fmt.Println("Second largest:", slice[len(slice)-2])
}
16. Write a function that returns the greatest common divisor (GCD) of two numbers.
go
package main
import "fmt"
func gcd(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}
func main() {
fmt.Println(gcd(48, 18))
}
17. Write a struct Rectangle with fields length and width, a method to compute area.
go
package main
import "fmt"
type Rectangle struct {
length, width float64
}
func (r Rectangle) Area() float64 {
return r.length * r.width
}
func main() {
r := Rectangle{5, 3}
fmt.Println("Area:", r.Area())
}
18. Write a program that demonstrates function overloading (not supported, but use variadic or different signatures).
go
package main
import "fmt"
func addInts(a, b int) int {
return a + b
}
func addFloats(a, b float64) float64 {
return a + b
}
func main() {
fmt.Println(addInts(5, 10))
fmt.Println(addFloats(2.5, 3.7))
}
19. Write a program that creates a Student struct with name and roll number, then prints using a method.
go
package main
import "fmt"
type Student struct {
name string
roll int
}
func (s Student) Display() {
fmt.Printf("Name: %s, Roll: %d\n", s.name, s.roll)
}
func main() {
s := Student{"Alice", 101}
s.Display()
}
20. Write a program that uses an interface Shape with method Area(), and implements for Rectangle and Circle.
go
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
}
type Rectangle struct {
w, h float64
}
func (r Rectangle) Area() float64 { return r.w * r.h }
type Circle struct {
r float64
}
func (c Circle) Area() float64 { return math.Pi * c.r * c.r }
func main() {
shapes := []Shape{Rectangle{3, 4}, Circle{5}}
for _, s := range shapes {
fmt.Printf("Area: %.2f\n", s.Area())
}
}
Also try it: 100 Laravel practice problems with solutions
21. Write a program that handles division by zero using error handling (return error).
go
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
res, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", res)
}
}
22. Write a program that reads a line from the user and prints its length.
go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter a string: ")
line, _ := reader.ReadString('\n')
fmt.Println("Length:", len(line)-1) // -1 for newline
}
23. Write a program that counts the number of words in a sentence using strings.Fields.
go
package main
import (
"fmt"
"strings"
)
func main() {
sentence := "The quick brown fox"
words := strings.Fields(sentence)
fmt.Println("Word count:", len(words))
}
24. Write a program that converts a slice of strings to uppercase.
go
package main
import (
"fmt"
"strings"
)
func main() {
words := []string{"apple", "banana", "cherry"}
for i, w := range words {
words[i] = strings.ToUpper(w)
}
fmt.Println(words)
}
25. Write a program that uses a map to count the frequency of words in a string.
go
package main
import (
"fmt"
"strings"
)
func main() {
text := "the cat and the dog and the bird"
words := strings.Fields(text)
freq := make(map[string]int)
for _, w := range words {
freq[w]++
}
fmt.Println(freq)
}
26. Write a program that checks if a string contains only digits.
go
package main
import (
"fmt"
"unicode"
)
func main() {
str := "12345"
allDigits := true
for _, ch := range str {
if !unicode.IsDigit(ch) {
allDigits = false
break
}
}
fmt.Println(allDigits)
}
27. Write a program that finds the common elements between two slices.
go
package main
import "fmt"
func main() {
s1 := []int{1, 2, 3, 4}
s2 := []int{3, 4, 5, 6}
set := make(map[int]bool)
for _, v := range s1 {
set[v] = true
}
var common []int
for _, v := range s2 {
if set[v] {
common = append(common, v)
}
}
fmt.Println(common)
}
28. Write a program that squares each element of a slice using a loop.
go
package main
import "fmt"
func main() {
nums := []int{1, 2, 3, 4}
for i, v := range nums {
nums[i] = v * v
}
fmt.Println(nums)
}
29. Write a program that writes a string to a file named “output.txt” and then reads it back.
go
package main
import (
"fmt"
"os"
)
func main() {
data := []byte("Hello Go")
err := os.WriteFile("output.txt", data, 0644)
if err != nil {
fmt.Println("Write error:", err)
return
}
content, err := os.ReadFile("output.txt")
if err != nil {
fmt.Println("Read error:", err)
return
}
fmt.Println(string(content))
}
30. Write a program that uses recursion to compute the factorial of a number.
go
package main
import "fmt"
func fact(n int) int {
if n <= 1 {
return 1
}
return n * fact(n-1)
}
func main() {
fmt.Println(fact(5))
}
31. Write a program that prints the multiplication table (1 to 10) for a given number.
go
package main
import "fmt"
func main() {
n := 7
for i := 1; i <= 10; i++ {
fmt.Printf("%d x %d = %d\n", n, i, n*i)
}
}
32. Write a program that removes all whitespace from a string.
go
package main
import (
"fmt"
"strings"
)
func main() {
str := " Hello World "
result := strings.ReplaceAll(str, " ", "")
fmt.Println(result)
}
33. Write a program that swaps two numbers without using a third variable.
go
package main
import "fmt"
func main() {
a, b := 5, 10
a, b = b, a
fmt.Println("a=", a, "b=", b)
}
34. Write a program that creates a map of name to age and prints it.
go
package main
import "fmt"
func main() {
ages := map[string]int{"Alice": 25, "Bob": 30}
for name, age := range ages {
fmt.Printf("%s: %d\n", name, age)
}
}
35. Write a program that sorts a slice of strings alphabetically.
go
package main
import (
"fmt"
"sort"
)
func main() {
words := []string{"banana", "apple", "cherry"}
sort.Strings(words)
fmt.Println(words)
}
36. Write a program that finds the first non-repeated character in a string “swiss”.
go
package main
import "fmt"
func firstNonRepeated(s string) byte {
count := make(map[byte]int)
for i := 0; i < len(s); i++ {
count[s[i]]++
}
for i := 0; i < len(s); i++ {
if count[s[i]] == 1 {
return s[i]
}
}
return 0
}
func main() {
str := "swiss"
fmt.Printf("%c\n", firstNonRepeated(str))
}
37. Write a program that checks if two strings are anagrams (e.g., “listen” and “silent”).
go
package main
import (
"fmt"
"sort"
"strings"
)
func sortString(s string) string {
chars := strings.Split(s, "")
sort.Strings(chars)
return strings.Join(chars, "")
}
func main() {
s1, s2 := "listen", "silent"
if sortString(s1) == sortString(s2) {
fmt.Println("Anagrams")
} else {
fmt.Println("Not anagrams")
}
}
38. Write a program that implements a simple counter using a closure.
go
package main
import "fmt"
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
func main() {
c := counter()
fmt.Println(c())
fmt.Println(c())
}
Also try it: 100 Redux practice problems with solutions
39. Write a program that uses defer to print a message after a function returns.
go
package main
import "fmt"
func main() {
defer fmt.Println("World")
fmt.Print("Hello ")
}
40. Write a program that generates a random integer between 1 and 100.
go
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(rand.Intn(100) + 1)
}
41. Write a program that rotates a slice to the left by k positions (k=2).
go
package main
import "fmt"
func rotateLeft(s []int, k int) []int {
k = k % len(s)
return append(s[k:], s[:k]...)
}
func main() {
s := []int{1, 2, 3, 4, 5}
fmt.Println(rotateLeft(s, 2))
}
42. Write a program that finds the missing number in an array of 1..n (e.g., {1,2,3,5} missing 4).
go
package main
import "fmt"
func main() {
arr := []int{1, 2, 3, 5}
n := 5
total := n * (n + 1) / 2
sum := 0
for _, v := range arr {
sum += v
}
fmt.Println("Missing:", total-sum)
}
43. Write a program that merges two sorted slices into one sorted slice.
go
package main
import "fmt"
func mergeSorted(a, b []int) []int {
result := make([]int, 0, len(a)+len(b))
i, j := 0, 0
for i < len(a) && j < len(b) {
if a[i] < b[j] {
result = append(result, a[i])
i++
} else {
result = append(result, b[j])
j++
}
}
result = append(result, a[i:]...)
result = append(result, b[j:]...)
return result
}
func main() {
a := []int{1, 3, 5}
b := []int{2, 4, 6}
fmt.Println(mergeSorted(a, b))
}
44. Write a program that computes the power of a number using recursion (x^n).
go
package main
import "fmt"
func power(base, exp int) int {
if exp == 0 {
return 1
}
return base * power(base, exp-1)
}
func main() {
fmt.Println(power(2, 5))
}
45. Write a program that checks if a string is a valid palindrome considering only alphanumeric characters.
go
package main
import (
"fmt"
"regexp"
"strings"
)
func isAlphaNumericPalindrome(s string) bool {
reg := regexp.MustCompile(`[^a-zA-Z0-9]+`)
cleaned := reg.ReplaceAllString(s, "")
cleaned = strings.ToLower(cleaned)
for i := 0; i < len(cleaned)/2; i++ {
if cleaned[i] != cleaned[len(cleaned)-1-i] {
return false
}
}
return true
}
func main() {
s := "A man, a plan, a canal: Panama"
fmt.Println(isAlphaNumericPalindrome(s))
}
46. Write a program that creates a goroutine to print “Hello” and the main function prints “World”.
go
package main
import (
"fmt"
"time"
)
func main() {
go fmt.Println("Hello")
time.Sleep(time.Millisecond)
fmt.Println("World")
}
47. Write a program that uses a channel to send a number from one goroutine to the main goroutine.
go
package main
import "fmt"
func main() {
ch := make(chan int)
go func() {
ch <- 42
}()
fmt.Println(<-ch)
}
48. Write a program that implements a worker pool using goroutines and channels.
go
package main
import (
"fmt"
"sync"
)
func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for j := range jobs {
results <- j * j
}
}
func main() {
const numJobs = 10
const numWorkers = 3
jobs := make(chan int, numJobs)
results := make(chan int, numJobs)
var wg sync.WaitGroup
for w := 1; w <= numWorkers; w++ {
wg.Add(1)
go worker(w, jobs, results, &wg)
}
for j := 1; j <= numJobs; j++ {
jobs <- j
}
close(jobs)
wg.Wait()
close(results)
for res := range results {
fmt.Println(res)
}
}
49. Write a program that uses select to wait on two channels.
go
package main
import (
"fmt"
"time"
)
func main() {
ch1 := make(chan string)
ch2 := make(chan string)
go func() {
time.Sleep(1 * time.Second)
ch1 <- "one"
}()
go func() {
time.Sleep(2 * time.Second)
ch2 <- "two"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-ch1:
fmt.Println(msg1)
case msg2 := <-ch2:
fmt.Println(msg2)
}
}
}
50. Write a program that reads a JSON string (map) and unmarshals it into a struct.
go
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
jsonStr := `{"name":"John","age":30}`
var p Person
json.Unmarshal([]byte(jsonStr), &p)
fmt.Printf("%+v\n", p)
}
51. Write a program that uses sort.Slice to sort a slice of structs by a field.
go
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
func main() {
people := []Person{{"Alice", 25}, {"Bob", 20}, {"Charlie", 30}}
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})
fmt.Println(people)
}
52. Write a program that implements a simple stack using a slice.
go
package main
import "fmt"
type Stack []int
func (s *Stack) Push(v int) {
*s = append(*s, v)
}
func (s *Stack) Pop() int {
if len(*s) == 0 {
return -1
}
val := (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
return val
}
func main() {
s := Stack{}
s.Push(10)
s.Push(20)
fmt.Println(s.Pop())
fmt.Println(s.Pop())
}
53. Write a program that uses sync.Mutex to protect a shared counter from race conditions.
go
package main
import (
"fmt"
"sync"
)
var counter int
var mu sync.Mutex
func increment(wg *sync.WaitGroup) {
defer wg.Done()
for i := 0; i < 1000; i++ {
mu.Lock()
counter++
mu.Unlock()
}
}
func main() {
var wg sync.WaitGroup
wg.Add(2)
go increment(&wg)
go increment(&wg)
wg.Wait()
fmt.Println(counter)
}
54. Write a program that uses time.Tick to print a message every second (stop after 5).
go
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
done := time.After(5 * time.Second)
for {
select {
case <-ticker.C:
fmt.Println("Tick")
case <-done:
fmt.Println("Done")
return
}
}
}
55. Write a program that implements a simple HTTP server that responds with “Hello”.
go
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
56. Write a program that downloads a webpage’s content using net/http.
go
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("https://example.com")
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body[:200]))
}
57. Write a program that parses command-line arguments using the os package.
go
package main
import (
"fmt"
"os"
)
func main() {
args := os.Args[1:]
fmt.Println("Arguments:", args)
}
58. Write a program that uses strings.Join to concatenate a slice of strings with commas.
go
package main
import (
"fmt"
"strings"
)
func main() {
words := []string{"apple", "banana", "cherry"}
result := strings.Join(words, ", ")
fmt.Println(result)
}
59. Write a program that finds the longest word in a sentence.
go
package main
import (
"fmt"
"strings"
)
func longestWord(sentence string) string {
words := strings.Fields(sentence)
longest := ""
for _, w := range words {
if len(w) > len(longest) {
longest = w
}
}
return longest
}
func main() {
fmt.Println(longestWord("The quick brown fox jumps over the lazy dog"))
}
60. Write a program that uses regexp to find all email addresses in a string.
go
package main
import (
"fmt"
"regexp"
)
func main() {
text := "Contact us at john@example.com and jane@example.org"
re := regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`)
emails := re.FindAllString(text, -1)
fmt.Println(emails)
}
61. Write a program that implements a simple linked list node and prints it.
go
package main
import "fmt"
type Node struct {
data int
next *Node
}
func main() {
head := &Node{data: 1}
head.next = &Node{data: 2}
head.next.next = &Node{data: 3}
for n := head; n != nil; n = n.next {
fmt.Print(n.data, " ")
}
}
Also try it: 100 Docker practice problems with solutions
62. Write a program that reverses a linked list.
go
package main
import "fmt"
type Node struct {
data int
next *Node
}
func reverse(head *Node) *Node {
var prev *Node
curr := head
for curr != nil {
next := curr.next
curr.next = prev
prev = curr
curr = next
}
return prev
}
func main() {
head := &Node{1, &Node{2, &Node{3, nil}}}
rev := reverse(head)
for n := rev; n != nil; n = n.next {
fmt.Print(n.data, " ")
}
}
63. Write a program that uses go test unit testing (simple test for a function).
go
// In a file called math.go
package math
func Add(a, b int) int {
return a + b
}
// In a file called math_test.go
package math
import "testing"
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Expected 5, got %d", result)
}
}
64. Write a program that uses context to cancel a goroutine after a timeout.
go
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
go func() {
select {
case <-ctx.Done():
fmt.Println("Cancelled")
}
}()
time.Sleep(2 * time.Second)
}
65. Write a program that implements a simple flag parser for command-line options.
go
package main
import (
"flag"
"fmt"
)
func main() {
name := flag.String("name", "Guest", "your name")
flag.Parse()
fmt.Println("Hello", *name)
}
66. Write a program that uses strconv to convert a string to an integer and handle errors.
go
package main
import (
"fmt"
"strconv"
)
func main() {
s := "123"
i, err := strconv.Atoi(s)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(i)
}
67. Write a program that uses panic and recover to handle a runtime error.
go
package main
import "fmt"
func safeDivide(a, b int) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered:", r)
}
}()
if b == 0 {
panic("division by zero")
}
fmt.Println(a / b)
}
func main() {
safeDivide(10, 0)
fmt.Println("Continuing")
}
68. Write a program that reads a CSV file and prints its rows.
go
package main
import (
"encoding/csv"
"fmt"
"os"
)
func main() {
file, _ := os.Open("data.csv")
defer file.Close()
reader := csv.NewReader(file)
records, _ := reader.ReadAll()
for _, row := range records {
fmt.Println(row)
}
}
69. Write a program that creates a zip archive containing a single file.
go
package main
import (
"archive/zip"
"os"
)
func main() {
f, _ := os.Create("archive.zip")
defer f.Close()
zw := zip.NewWriter(f)
defer zw.Close()
w, _ := zw.Create("hello.txt")
w.Write([]byte("Hello, World!"))
}
70. Write a program that uses embed to embed a text file into the binary (Go 1.16+).
go
//go:embed hello.txt
var content string
func main() {
print(content)
}
71. Write a program that computes the median of a slice of floats.
go
package main
import (
"fmt"
"sort"
)
func median(nums []float64) float64 {
sort.Float64s(nums)
n := len(nums)
if n%2 == 0 {
return (nums[n/2-1] + nums[n/2]) / 2.0
}
return nums[n/2]
}
func main() {
vals := []float64{3.5, 7.2, 1.8, 9.1, 4.0}
fmt.Println(median(vals))
}
72. Write a program that implements a simple logging function with different levels.
go
package main
import (
"log"
"os"
)
var (
Info = log.New(os.Stdout, "INFO: ", log.Ldate|log.Ltime)
Error = log.New(os.Stderr, "ERROR: ", log.Ldate|log.Ltime)
)
func main() {
Info.Println("Application started")
Error.Println("Something went wrong")
}
73. Write a program that uses sync.Once to initialize a singleton.
go
package main
import (
"fmt"
"sync"
)
type Singleton struct{}
var instance *Singleton
var once sync.Once
func GetInstance() *Singleton {
once.Do(func() {
instance = &Singleton{}
})
return instance
}
func main() {
s1 := GetInstance()
s2 := GetInstance()
fmt.Println(s1 == s2)
}
74. Write a program that uses context to pass values (context.WithValue).
go
package main
import (
"context"
"fmt"
)
type key string
func main() {
ctx := context.WithValue(context.Background(), key("user"), "Alice")
val := ctx.Value(key("user"))
fmt.Println(val)
}
75. Write a program that implements a simple REST API endpoint using gorilla/mux (alternative to net/http).
go
// Requires: go get github.com/gorilla/mux
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/hello/{name}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
fmt.Fprintf(w, "Hello %s", vars["name"])
})
http.ListenAndServe(":8080", r)
}
76. Write a program that uses go generate to generate code (simple comment).
go
//go:generate echo "Generated file"
package main
func main() {}
77. Write a program that uses json.Marshal to convert a struct to JSON.
go
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string
Age int
}
func main() {
u := User{"Alice", 30}
b, _ := json.Marshal(u)
fmt.Println(string(b))
}
78. Write a program that uses http.Client to make a POST request with JSON body.
go
package main
import (
"bytes"
"encoding/json"
"net/http"
)
type Payload struct {
Name string `json:"name"`
}
func main() {
data := Payload{Name: "John"}
jsonData, _ := json.Marshal(data)
http.Post("https://httpbin.org/post", "application/json", bytes.NewBuffer(jsonData))
}
79. Write a program that implements a simple rate limiter using a ticker.
go
package main
import (
"fmt"
"time"
)
func main() {
limiter := time.Tick(200 * time.Millisecond)
for i := 0; i < 5; i++ {
<-limiter
fmt.Println("Request", i+1)
}
}
80. Write a program that uses sync.WaitGroup to wait for multiple goroutines.
go
package main
import (
"fmt"
"sync"
)
func worker(wg *sync.WaitGroup, id int) {
defer wg.Done()
fmt.Printf("Worker %d done\n", id)
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go worker(&wg, i)
}
wg.Wait()
fmt.Println("All workers finished")
}
81. Write a program that uses atomic package to increment a counter without mutex.
go
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var counter int32
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
atomic.AddInt32(&counter, 1)
wg.Done()
}()
}
wg.Wait()
fmt.Println(counter)
}
82. Write a program that uses time.AfterFunc to schedule a function.
go
package main
import (
"fmt"
"time"
)
func main() {
time.AfterFunc(2*time.Second, func() {
fmt.Println("Delayed print")
})
time.Sleep(3 * time.Second)
}
83. Write a program that reads an environment variable and prints it.
go
package main
import (
"fmt"
"os"
)
func main() {
value := os.Getenv("GOPATH")
fmt.Println("GOPATH:", value)
}
84. Write a program that uses strings.Replacer to replace multiple substrings.
go
package main
import (
"fmt"
"strings"
)
func main() {
replacer := strings.NewReplacer("old", "new", "bad", "good")
result := replacer.Replace("old bad thing")
fmt.Println(result)
}
85. Write a program that implements a simple binary search tree (insert and search).
go
package main
import "fmt"
type BST struct {
val int
left *BST
right *BST
}
func (b *BST) Insert(v int) {
if v < b.val {
if b.left == nil {
b.left = &BST{val: v}
} else {
b.left.Insert(v)
}
} else if v > b.val {
if b.right == nil {
b.right = &BST{val: v}
} else {
b.right.Insert(v)
}
}
}
func (b *BST) Search(v int) bool {
if b == nil {
return false
}
if v == b.val {
return true
}
if v < b.val {
return b.left.Search(v)
}
return b.right.Search(v)
}
func main() {
root := &BST{val: 5}
root.Insert(3)
root.Insert(7)
fmt.Println(root.Search(3))
fmt.Println(root.Search(8))
}
86. Write a program that uses pprof for profiling (simple CPU profile).
go
package main
import (
"os"
"runtime/pprof"
)
func main() {
f, _ := os.Create("cpu.prof")
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
// heavy computation
for i := 0; i < 100000000; i++ {
}
}
87. Write a program that uses testing/quick to perform property-based testing.
go
// In a test file
import "testing/quick"
func TestReverse(t *testing.T) {
f := func(s []byte) bool {
rev := reverse(s)
return string(rev) == string(s) // trivial, just example
}
if err := quick.Check(f, nil); err != nil {
t.Error(err)
}
}
88. Write a program that uses go mod to create a module (module declaration).
go
// In go.mod file:
module example.com/myapp
go 1.21
// In main.go
package main
func main() {}
89. Write a program that uses text/template to substitute values into a template.
go
package main
import (
"os"
"text/template"
)
func main() {
tmpl, _ := template.New("test").Parse("Hello {{.Name}}")
data := struct{ Name string }{Name: "Alice"}
tmpl.Execute(os.Stdout, data)
}
90. Write a program that uses html/template to safely render HTML.
go
package main
import (
"html/template"
"os"
)
func main() {
tmpl, _ := template.New("test").Parse(`<h1>{{.Title}}</h1>`)
data := struct{ Title string }{Title: "Go HTML"}
tmpl.Execute(os.Stdout, data)
}
Also try it: 100 NumPy practice problems with solutions
91. Write a program that implements a simple TCP echo server.
go
package main
import (
"bufio"
"net"
"strings"
)
func handle(conn net.Conn) {
defer conn.Close()
r := bufio.NewReader(conn)
for {
msg, err := r.ReadString('\n')
if err != nil {
return
}
conn.Write([]byte("Echo: " + strings.TrimSpace(msg) + "\n"))
}
}
func main() {
ln, _ := net.Listen("tcp", ":8080")
for {
conn, _ := ln.Accept()
go handle(conn)
}
}
92. Write a program that uses net/url to parse a URL and extract components.
go
package main
import (
"fmt"
"net/url"
)
func main() {
u, _ := url.Parse("https://example.com:8080/path?q=go")
fmt.Println("Scheme:", u.Scheme)
fmt.Println("Host:", u.Host)
fmt.Println("Path:", u.Path)
fmt.Println("Query:", u.Query().Get("q"))
}
93. Write a program that uses bytes.Buffer to efficiently concatenate strings.
go
package main
import (
"bytes"
"fmt"
)
func main() {
var buf bytes.Buffer
for i := 0; i < 5; i++ {
buf.WriteString("Hello ")
}
fmt.Println(buf.String())
}
94. Write a program that uses io.Copy to copy data from a file to stdout.
go
package main
import (
"io"
"os"
)
func main() {
f, _ := os.Open("input.txt")
defer f.Close()
io.Copy(os.Stdout, f)
}
95. Write a program that uses select with a timeout for channel operations.
go
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
select {
case <-ch:
fmt.Println("Received")
case <-time.After(1 * time.Second):
fmt.Println("Timeout")
}
}
96. Write a program that uses sync.Cond to signal between goroutines.
go
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var mu sync.Mutex
cond := sync.NewCond(&mu)
ready := false
go func() {
time.Sleep(1 * time.Second)
mu.Lock()
ready = true
cond.Signal()
mu.Unlock()
}()
mu.Lock()
for !ready {
cond.Wait()
}
fmt.Println("Ready!")
mu.Unlock()
}
97. Write a program that uses math/big to compute large factorial (beyond 64-bit).
go
package main
import (
"fmt"
"math/big"
)
func main() {
n := 50
fact := big.NewInt(1)
for i := 1; i <= n; i++ {
fact.Mul(fact, big.NewInt(int64(i)))
}
fmt.Println(fact)
}
98. Write a program that uses crypto/sha256 to compute hash of a string.
go
package main
import (
"crypto/sha256"
"fmt"
)
func main() {
data := []byte("hello")
hash := sha256.Sum256(data)
fmt.Printf("%x", hash)
}
99. Write a program that uses os/signal to handle SIGINT (Ctrl+C).
go
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
fmt.Println("\nExiting...")
os.Exit(0)
}()
fmt.Println("Press Ctrl+C to exit")
select {}
}
100. Write a program that implements a simple command-line calculator using os.Args.
go
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) != 4 {
fmt.Println("Usage: calc <num1> <op> <num2>")
return
}
a, _ := strconv.ParseFloat(os.Args[1], 64)
b, _ := strconv.ParseFloat(os.Args[3], 64)
op := os.Args[2]
var res float64
switch op {
case "+":
res = a + b
case "-":
res = a - b
case "*":
res = a * b
case "/":
res = a / b
default:
fmt.Println("Invalid operator")
return
}
fmt.Println(res)
}
Final Thoughts
Completing these 100 Go (Golang) practice problems with solutions shows your dedication to learning and improving. Each problem helped you understand Go’s simplicity, speed, and powerful features a little better.
Even if some questions felt tough, every attempt made your thinking sharper and your coding stronger. Keep practicing, stay curious, and continue building with Go—because every small step you take today brings you closer to becoming a confident developer tomorrow.