/
Text
Description:
If you want to master Golang through practice, this book is for you!
This book is a test of your skills. Each task is a step toward improving your abilities and gaining a deep
understanding of the language.
Develop your skills through practice, and you'll learn to solve problems encountered in real projects.
The book contains no theory, only practical tasks that will help you observe and feel your progress.
Unleash your potential!
Table of Contents
Tasks:
Syntax and program structure ----- 4
Variables and data types ----- 6
Control structures (if, for, switch) ----- 8
Functions and their declaration ----- 10
Arrays, slices, and maps ----- 12
Pointers and memory management ----- 14
Structs and methods ----- 16
Interfaces and their usage ----- 18
Packages and modules ----- 20
Error handling ----- 22
Solutions:
Syntax and program structure ----- 24
Variables and data types ----- 29
Control structures (if, for, switch) ----- 34
Functions and their declaration ----- 40
Arrays, slices, and maps ----- 46
Pointers and memory management ----- 52
Structs and methods ----- 58
Interfaces and their usage ----- 65
Packages and modules ----- 74
Error handling ----- 83
Golang Tasks: Syntax and Program Structure
Task 1
Write a program that prints "Hello, Golang!".
Task 2
Declare a variable name of type string and print its value.
Task 3
Declare two variables x and y of type int and print their sum.
Task 4
Create a constant pi with the value 3.14 and print it.
Task 5
Write a program that declares a variable age of type int and assigns it the value 25.
Task 6
Use short variable declaration to create a variable count with the value 10 and print it.
Task 7
Declare two variables a and b of type float64, assign them the values 5.5 and 3.3, and print their
difference.
Task 8
Create a program that declares a variable isActive of type bool and prints its value.
Task 9
Write a program that prints the type of the variable message if message is declared as a string.
Task 10
Create two constants width and height of type int and print their product.
Task 11
Declare a variable temperature of type float32 with the initial value 23.5 and print it.
Task 12
Use short variable declaration to create a variable price with the value 99.99 and print it.
Task 13
Create a program that declares a variable x of type uint and prints its value.
Task 14
Declare a variable greeting of type string with the initial value "Hello, Go!" and print it.
Task 15
Create a constant maxScore with the value 100 and print it.
Task 16
Declare two variables m and n of type int, assign them the values 8 and 3, and print their quotient.
Task 17
Write a program that declares a variable isSunny of type bool with the value true and prints it.
Task 18
Create a program that declares a variable speed of type float64 and prints its value.
Task 19
Use short variable declaration to create a variable color with the value "red" and print it.
Task 20
Declare a variable distance of type int with the initial value 150 and print it.
Golang Tasks: Variables and Data Types
Task 1
Declare a variable x of type int and assign it the value 42.
Task 2
Create a variable message of type string with the initial value "Hello, Go!".
Task 3
Declare a variable pi of type float64 with the value 3.14159 .
Task 4
Create a variable isValid of type bool with the initial value true.
Task 5
Declare a variable count of type uint and assign it the value 100.
Task 6
Use short variable declaration to create a variable price with the value 19.99 .
Task 7
Declare a variable temperature of type float32 with the initial value -10 .5 .
Task 8
Create a variable id of type int64 and assign it the value 123456.
Task 9
Declare a variable name of type string and print its type.
Task 10
Create a variable speed of type float64 with the initial value 65.5 .
Task 11
Declare a variable score of type int with the initial value 85.
Task 12
Use short variable declaration to create a variable color with the value "blue".
Task 13
Create a variable height of type int32 and assign it the value 175.
Task 14
Declare a variable isActive of type bool with the initial value false.
Task 15
Create a variable distance of type uint64 with the initial value 1000.
Task 16
Declare a variable weight of type float32 with the initial value 70.5 .
Task 17
Use short variable declaration to create a variable city with the value "New York".
Task 18
Create a variable code of type int16 and assign it the value 255.
Task 19
Declare a variable enabled of type bool and print its type.
Task 20
Create a variable rate of type float64 with the initial value 4.5 .
Golang Tasks: Control Structures (if, for, switch)
Task 1
Write a program that checks if a number is positive using if.
Task 2
Create a program that prints numbers from 1 to 5 using a for loop.
Task 3
Use switch to check the value of a variable day (int) and print the day of the week (1 - Monday, ..., 7 -
Sunday).
Task 4
Write a program that checks if a number is even using if-else.
Task 5
Create a for loop that prints even numbers from 2 to 10.
Task 6
Use switch for a variable grade (string) and print: "A" - Excellent, "B" - Good, "C" - Satisfactory, default -
Unknown.
Task 7
Write a program with if-else-if to check age: if age < 18, print "Minor", if age >= 18, print "Adult".
Task 8
Create a for loop that sums numbers from 1 to 10.
Task 9
Use switch for a variable month (int) and print the month name (1 - January, ..., 12 - December).
Task 10
Write a program that checks if a number is greater than 100 using if.
Task 11
Create a for loop that prints numbers from 10 to 1 in reverse order.
Task 12
Use switch for a variable color (string) and print: "red" - Red, "blue" - Blue, default - Unknown color.
Task 13
Write a program with if-else that compares two numbers and prints the larger one.
Task 14
Create a for loop that prints the multiplication table for the number 5 (from 1 to 10).
Task 15
Use switch for a variable score (int) and print: 90-100 - "A", 80-89 - "B", 70-79 - "C", default - "F".
Task 16
Write a program that checks if a year is a leap year (divisible by 4) using if.
Task 17
Create a for loop that prints the first 5 Fibonacci numbers (0, 1, 1, 2, 3).
Task 18
Use switch for a variable season (int) and print: 1 - Winter, 2 - Spring, 3 - Summer, 4 - Fall.
Task 19
Write a program with if-else-if that checks temperature: if temp < 0 - "Cold", 0-20 - "Cool", above 20 -
"Warm".
Task 20
Create a for loop that calculates the factorial of the number 5.
Golang Tasks: Functions and Their Declaration
Task 1
Write a function greet() that prints "Hello, Golang!".
Task 2
Create a function add(a, b int) that returns the sum of two numbers.
Task 3
Write a function square(num int) that returns the square of a number.
Task 4
Create a function sayHello(name string) that prints "Hello, [name]!".
Task 5
Write a function isEven(num int) that returns true if the number is even.
Task 6
Create a function max(a, b int) that returns the larger of two numbers.
Task 7
Write a function getArea(radius float64) that returns the area of a circle (π * r^2).
Task 8
Create a function printNumbers(n int) that prints numbers from 1 to n.
Task 9
Write a function double(num int) that returns the doubled value of a number.
Task 10
Create a function isPositive(num int) that returns true if the number is positive.
Task 11
Write a function swap(a, b int) that returns two numbers in reverse order.
Task 12
Create a function factorial(n int) that returns the factorial of n.
Task 13
Write a function greetUser(name string, age int) that prints "Hello, [name], you are [age] years old!".
Task 14
Create a function average(a, b float64) that returns the average of two numbers.
Task 15
Write a function isZero(num int) that returns true if the number is zero.
Task 16
Create a function min(a, b int) that returns the smaller of two numbers.
Task 17
Write a function sumToN(n int) that returns the sum of numbers from 1 to n.
Task 18
Create a function convertToFahrenheit(celsius float64) that converts temperature from Celsius to
Fahrenheit (C*9/5 + 32).
Task 19
Write a function isGreaterThanTen(num int) that returns true if the number is greater than 10.
Task 20
Create a function multiply(a, b, c int) that returns the product of three numbers.
Golang Tasks: Arrays, Slices, and Maps
Task 1
Declare an array of 5 integers and print its elements.
Task 2
Create a slice of 3 strings and print its length.
Task 3
Create a map where keys are names (string) and values are ages (int), and add 2 entries.
Task 4
Declare an array of 4 numbers and find the sum of its elements.
Task 5
Create a slice of 5 numbers and append one more number to it.
Task 6
Create a map where keys are days of the week (string) and values are true/false (open/closed), and check
if "Monday" is open.
Task 7
Declare an array of 3 strings and replace the second element with "Golang".
Task 8
Create a slice of 4 numbers and print only the first 2 elements.
Task 9
Create a map with key-value pairs (string-int) and delete one entry.
Task 10
Declare an array of 5 numbers and find the maximum element.
Task 11
Create a slice of 6 numbers and remove the last element.
Task 12
Create a map where keys are fruit names and values are their quantities, and print the total quantity of
fruits.
Task 13
Declare an array of 3 numbers and increment each element by 1.
Task 14
Create a slice of 5 strings and sort it in alphabetical order.
Task 15
Create a map with key-value pairs (string-string) and check if the key "color" exists.
Task 16
Declare an array of 4 numbers and find the average.
Task 17
Create a slice of 3 numbers and create a new slice with doubled values.
Task 18
Create a map where keys are country names and values are their capitals, and print the capital of
"France".
Task 19
Declare an array of 5 numbers and check if it contains the number 42.
Task 20
Create a slice of 4 numbers and copy it into a new slice.
Golang Tasks: Pointers and Memory
Management
Task 1
Declare a variable and print its memory address.
Task 2
Create a pointer to an integer and print its value.
Task 3
Write a function that takes a pointer to an int and increases its value by 10.
Task 4
Create a pointer to a string and change its value through the pointer.
Task 5
Declare a pointer to a float64 and assign a value to it using the new operator.
Task 6
Write a function that takes a pointer to a bool and toggles its value.
Task 7
Create a pointer to an array of 3 elements and print its first element.
Task 8
Declare a pointer to a slice and append a new element to the slice through the pointer.
Task 9
Write a function that takes a pointer to a map[string]int and adds a new key-value pair.
Task 10
Create a pointer to a pointer to an int and print its value.
Task 11
Write a function that takes a pointer to an int and resets its value to zero.
Task 12
Create a pointer to a struct with a Name (string) field and change the field’s value through the pointer.
Task 13
Declare a pointer to an int, set it to nil, and check if it is nil.
Task 14
Write a function that takes a pointer to a slice and doubles each of its elements.
Task 15
Create a pointer to a map[string]string and delete one entry through the pointer.
Task 16
Write a function that takes two pointers to int and swaps their values.
Task 17
Create a pointer to a float64 using new and change its value.
Task 18
Declare a pointer to an array and change one of its elements through the pointer.
Task 19
Write a function that takes a pointer to a struct and updates one of its fields.
Task 20
Create a pointer to a slice and copy it into a new slice through the pointer.
Golang Tasks: Structs and Methods
Task 1
Create a Person struct with Name and Age fields, and print its values.
Task 2
Add a Greet method to the Person struct that prints a greeting with the name.
Task 3
Create a Rectangle struct with Width and Height fields, and an Area method to calculate the area.
Task 4
Create a Circle struct with a Radius field, and a Perimeter method to calculate the circle's perimeter.
Task 5
Create a Student struct with Name and Grade fields, and a Pass method that returns true if Grade >= 60.
Task 6
Create a Counter struct with a Value field, and Increment and Reset methods.
Task 7
Create a Book struct with Title and Pages fields, and an IsLong method that returns true if Pages > 300.
Task 8
Create a Car struct with Model and Speed fields, and an Accelerate method that increases the speed by
10.
Task 9
Create a Point struct with X and Y fields, and a DistanceFromOrigin method to calculate the distance from
the origin.
Task 10
Create an Employee struct with Name and Salary fields, and an IncreaseSalary method to increase the
salary by a given amount.
Task 11
Create a Box struct with Length, Width, and Height fields, and a Volume method to calculate the volume.
Task 12
Create an Account struct with a Balance field, and Deposit and Withdraw methods to manage the balance.
Task 13
Create a Triangle struct with Base and Height fields, and an Area method to calculate the triangle's area.
Task 14
Create a User struct with Username and Email fields, and an UpdateEmail method to change the email.
Task 15
Create a Product struct with Name and Price fields, and a Discount method to reduce the price by a given
percentage.
Task 16
Create a Timer struct with a Seconds field, and Start and Stop methods to manage the timer.
Task 17
Create a Vector struct with X and Y fields, and a Magnitude method to calculate the vector's length.
Task 18
Create a Library struct with a Books field (slice of strings), and an AddBook method to add a book.
Task 19
Create a Thermometer struct with a Temperature field (float64), and a ToFahrenheit method to convert the
temperature to Fahrenheit.
Task 20
Create a Player struct with Name and Score fields, and an AddPoints method to add points to the player.
Golang Tasks: Interfaces and Their Usage
Task 1
Create a Speaker interface with a Speak() method and implement it for a Person struct.
Task 2
Create a Shape interface with an Area() method and implement it for Rectangle and Circle structs.
Task 3
Create a Writer interface with a Write() method and implement it for a File struct.
Task 4
Create a Vehicle interface with a Move() method and implement it for Car and Bike structs.
Task 5
Create a Counter interface with an Increment() method and implement it for a SimpleCounter struct.
Task 6
Create a Printable interface with a Print() method and implement it for Book and Article structs.
Task 7
Create a Measurable interface with a Length() method and implement it for a Line struct.
Task 8
Create a Logger interface with a Log() method and implement it for a ConsoleLogger struct.
Task 9
Create a Stringer interface with a String() method and implement it for a User struct.
Task 10
Create a Resizable interface with a Resize() method and implement it for a Window struct.
Task 11
Create a Playable interface with a Play() method and implement it for Song and Video structs.
Task 12
Create a Mover interface with a Move() method and implement it for a Robot struct.
Task 13
Create a Calculator interface with an Add() method and implement it for a BasicCalculator struct.
Task 14
Create a Greeter interface with a Greet() method and implement it for Guest and Host structs.
Task 15
Create a Sorter interface with a Sort() method and implement it for a NumberSorter struct.
Task 16
Create a Reader interface with a Read() method and implement it for a Buffer struct.
Task 17
Create a Drawable interface with a Draw() method and implement it for Circle and Triangle structs.
Task 18
Create a Worker interface with a Work() method and implement it for an Employee struct.
Task 19
Create a Scalable interface with a Scale() method and implement it for an Image struct.
Task 20
Create a Notifier interface with a Notify() method and implement it for EmailNotifier and SMSNotifier
structs.
Golang Tasks: Packages and Modules
Task 1
Create a module greeting and a package hello with a function SayHello that returns a greeting.
Task 2
Create a module mathutils with a package calculator containing functions Add and Subtract.
Task 3
Create a module logger with a package log containing a function Info to print a message.
Task 4
Create a module shapes with a package geometry containing a Rectangle struct and an Area function.
Task 5
Create a module stringutils with a package reverse containing a function Reverse to reverse a string.
Task 6
Create a module counter with a package increment containing a Counter struct and an Inc method.
Task 7
Create a module timeutils with a package timer containing a function Now to get the current time.
Task 8
Create a module formatter with a package text containing a function Upper to convert a string to
uppercase.
Task 9
Create a module randomutils with a package dice containing a function Roll to generate a random number
from1to6.
Task 10
Create a module validator with a package check containing a function IsPositive to check if a number is
positive.
Task 11
Create a module fileutils with a package reader containing a function ReadContent to read a string (mock).
Task 12
Create a module converter with a package temperature containing a function CelsiusToFahrenheit.
Task 13
Create a module sorter with a package sort containing a function SortInts to sort a slice of numbers.
Task 14
Create a module notifier with a package notify containing a function Send to mock sending a notification.
Task 15
Create a module mathops with a package stats containing a function Average to compute the average of a
slice.
Task 16
Create a module encoder with a package base64 containing a function Encode to encode a string in
base64.
Task 17
Create a module parser with a package jsonparser containing a function Parse to mock JSON parsing.
Task 18
Create a module auth with a package user containing a User struct and a function Authenticate.
Task 19
Create a module generator with a package uuid containing a function Generate to mock UUID generation.
Task 20
Create a module cache with a package memory containing a Cache struct and a Get method.
Golang Tasks: Error Handling
Task 1
Write a function Divide that divides two numbers and returns an error if dividing by zero.
Task 2
Create a function ParseInt that parses a string into a number and returns an error if the string is invalid.
Task 3
Write a function FindElement that searches for an element in a slice and returns an error if not found.
Task 4
Create a function GetUser that returns a user by ID and an error if the user is not found.
Task 5
Write a function CheckPositive that checks if a number is positive and returns an error if not.
Task 6
Create a function ReadConfig that mocks reading a configuration and returns an error on failure.
Task 7
Write a function ValidateEmail that checks email validity and returns an error for an invalid format.
Task 8
Create a function OpenFile that mocks opening a file and returns an error if the file "does not exist".
Task 9
Write a function CalculateSquareRoot that computes the square root and returns an error for negative
numbers.
Task 10
Create a function CheckLength that checks a string's length and returns an error if the string is empty.
Task 11
Write a function ConnectDB that mocks connecting to a database and returns an error on failure.
Task 12
Create a function ParseDate that parses a date from a string and returns an error for an invalid format.
Task 13
Write a function CheckAge that checks if age is >= 18 and returns an error if the condition is not met.
Task 14
Create a function FetchData that mocks fetching data and returns an error on failure.
Task 15
Write a function ConvertToFloat that converts a string to float64 and returns an error on failure.
Task 16
Create a function CheckSlice that checks if a slice is empty and returns an error if it is.
Task 17
Write a function SendRequest that mocks sending a request and returns an error on failure.
Task 18
Create a function ValidatePassword that checks password length (min 8 chars) and returns an error if the
condition is not met.
Task 19
Write a function CheckEven that checks if a number is even and returns an error if not.
Task 20
Create a function ProcessData that mocks processing data and returns an error on failure.
Golang Solutions: Syntax and Program Structure
Task 1
package main
import "fmt"
func main() {
fmt.Println("Hello, Golang!")
}
Task 2
package main
import "fmt"
func main() {
var name string = "Alex"
fmt.Println(name)
}
Task 3
package main
import "fmt"
func main() {
varx,yint=10,20
fmt.Println(x + y)
}
Task 4
package main
import "fmt"
func main() {
const pi = 3.14
fmt.Println(pi)
}
Task 5
package main
import "fmt"
func main() {
varageint=25
fmt.Println(age)
}
Task 6
package main
import "fmt"
func main() {
count := 10
fmt.Println(count)
}
Task 7
package main
import "fmt"
func main() {
var a, b float64 = 5.5, 3.3
fmt.Println(a - b)
}
Task 8
package main
import "fmt"
func main() {
var isActive bool = true
fmt.Println(isActive)
}
Task 9
package main
import "fmt"
func main() {
message := "Hello"
fmt.Printf("Type: %T\n", m essage)
}
Task 10
package main
import "fmt"
func main() {
const width, height int = 5, 10
fmt.Println(width * height)
}
Task 11
package main
import "fmt"
func main() {
var temperature float32 = 23.5
fmt.Println(temperature)
}
Task 12
package main
import "fmt"
func main() {
price := 99.99
fmt.Println(price)
}
Task 13
package main
import "fmt"
func main() {
varxuint=42
fmt.Println(x)
}
Task 14
package main
import "fmt"
func main() {
var greeting string = "Hello, Go!"
fmt.Println(greeting)
}
Task 15
package main
import "fmt"
func main() {
const maxScore = 100
fmt.Println(maxScore)
}
Task 16
package main
import "fmt"
func main() {
varm,nint=8,3
fmt.Println(m / n)
}
Task 17
package main
import "fmt"
func main() {
var isSunny bool = true
fmt.Println(isSunny)
}
Task 18
package main
import "fmt"
func main() {
var speed float64 = 65.5
fmt.Println(speed)
}
Task 19
package main
import "fmt"
func main() {
color := "red"
fmt.Println(color)
}
Task 20
package main
import "fmt"
func main() {
var distance int = 150
fmt.Println(distance)
}
Golang Solutions: Variables and Data Types
Task 1
package main
import "fmt"
func main() {
varxint=42
fmt.Println(x)
}
Task 2
package main
import "fmt"
func main() {
var message string = "Hello, Go!"
fmt.Println(message)
}
Task 3
package main
import "fmt"
func main() {
var pi float64 = 3.14159
fmt.Println(pi)
}
Task 4
package main
import "fmt"
func main() {
var isValid bool = true
fmt.Println(isValid)
}
Task 5
package main
import "fmt"
func main() {
var count uint = 100
fmt.Println(count)
}
Task 6
package main
import "fmt"
func main() {
price := 19.99
fmt.Println(price)
}
Task 7
package main
import "fmt"
func main() {
var temperature float32 = -10.5
fmt.Println(temperature)
}
Task 8
package main
import "fmt"
func main() {
var id int64 = 123456
fmt.Println(id)
}
Task 9
package main
import "fmt"
func main() {
var name string = "Alex"
fmt.Printf("Type: %T\n", n ame)
}
Task 10
package main
import "fmt"
func main() {
var speed float64 = 65.5
fmt.Println(speed)
}
Task 11
package main
import "fmt"
func main() {
var score int = 85
fmt.Println(score)
}
Task 12
package main
import "fmt"
func main() {
color := "blue"
fmt.Println(color)
}
Task 13
package main
import "fmt"
func main() {
var height int32 = 175
fmt.Println(height)
}
Task 14
package main
import "fmt"
func main() {
var isActive bool = false
fmt.Println(isActive)
}
Task 15
package main
import "fmt"
func main() {
var distance uint64 = 1000
fmt.Println(distance)
}
Task 16
package main
import "fmt"
func main() {
var weight float32 = 70.5
fmt.Println(weight)
}
Task 17
package main
import "fmt"
func main() {
city := "New York"
fmt.Println(city)
}
Task 18
package main
import "fmt"
func main() {
var code int16 = 255
fmt.Println(code)
}
Task 19
package main
import "fmt"
func main() {
var enabled bool = true
fmt.Printf("Type: %T\n", e nabled)
}
Task 20
package main
import "fmt"
func main() {
var rate float64 = 4 .5
fmt.Println(rate)
}
Golang Solutions: Control Structures (if, for,
switch)
Task 1
package main
import "fmt"
func main() {
num := 42
ifnum>0{
fmt.Println("Number is positive")
}
}
Task 2
package main
import "fmt"
func main() {
fori:=1;i<=5;i++{
fmt.Println(i)
}
}
Task 3
package main
import "fmt"
func main() {
day:=1
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
default:
fmt.Println("Invalid day")
}
}
Task 4
package main
import "fmt"
func main() {
num:=8
ifnum%2==0{
fmt.Println("Number is even")
}else{
fmt.Println("Number is odd")
}
}
Task 5
package main
import "fmt"
func main() {
fori:=2;i<=10;i+=2{
fmt.Println(i)
}
}
Task 6
package main
import "fmt"
func main() {
grade := "A"
switch grade {
case "A":
fmt.Println("Excellent")
case "B":
fmt.Println("Good")
case "C":
fmt.Println("Satisfactory")
default:
fmt.Println("Unknown")
}
}
Task 7
package main
import "fmt"
func main() {
age := 20
ifage<18{
fmt.Println("Minor")
}elseifage>=18{
fmt.Println("Adult")
}
}
Task 8
package main
import "fmt"
func main() {
sum:=0
fori:=1;i<=10;i++{
sum+=i
}
fmt.Println(sum)
}
Task 9
package main
import "fmt"
func main() {
month := 1
switch month {
case 1:
fmt.Println("January")
case 2:
fmt.Println("February")
case 3:
fmt.Println("March")
case 4:
fmt.Println("April")
case 5:
fmt.Println("May")
case 6:
fmt.Println("June")
case 7:
fmt.Println("July")
case 8:
fmt.Println("August")
case 9:
fmt.Println("September")
case 10:
fmt.Println("October")
case 11:
fmt.Println("November")
case 12:
fmt.Println("December")
default:
fmt.Println("Invalid month")
}
}
Task 10
package main
import "fmt"
func main() {
num := 150
ifnum>100{
fmt.Println("Number is greater than 100")
}
}
Task 11
package main
import "fmt"
func main() {
fori:=10;i>=1;i--{
fmt.Println(i)
}
}
Task 12
package main
import "fmt"
func main() {
color := "red"
switch color {
case "red":
fmt.Println("Red")
case "blue":
fmt.Println("Blue")
default:
fmt.Println("Unknown color")
}
}
Task 13
package main
import "fmt"
func main() {
a,b:=10,20
ifa>b{
fmt.Println(a)
}else{
fmt.Println(b)
}
}
Task 14
package main
import "fmt"
func main() {
num:=5
fori:=1;i<=10;i++{
fmt.Printf("%d * %d = %d\n" , num, i, num*i)
}
}
Task 15
package main
import "fmt"
func main() {
score := 95
switch {
case score >= 90 && score <= 100:
fmt.Println("A")
case score >= 80 && score <= 89:
fmt.Println("B")
case score >= 70 && score <= 79:
fmt.Println("C")
default:
fmt.Println("F")
}
}
Task 16
package main
import "fmt"
func main() {
year := 2024
ifyear%4==0{
fmt.Println("Leap year")
}else{
fmt.Println("Not a leap year")
}
}
Task 17
package main
import "fmt"
func main() {
a,b:=0,1
fmt.Println(a)
fmt.Println(b)
fori:=0;i<3;i++{
c:=a+b
fmt.Println(c)
a,b=b,c
}
}
Task 18
package main
import "fmt"
func main() {
season := 1
switch season {
case 1:
fmt.Println("Winter")
case 2:
fmt.Println("Spring")
case 3:
fmt.Println("Summer")
case 4:
fmt.Println("Fall")
default:
fmt.Println("Invalid season")
}
}
Task 19
package main
import "fmt"
func main() {
temp := 25
iftemp<0{
fmt.Println("Cold")
}elseiftemp<=20{
fmt.Println("Cool")
}else{
fmt.Println("Warm")
}
}
Task 20
package main
import "fmt"
func main() {
num:=5
factorial := 1
fori:=1;i<=num;i++{
factorial *= i
}
fmt.Println(factorial)
}
Golang Solutions: Functions and Their
Declaration
Task 1
package main
import "fmt"
func greet() {
fmt.Println("Hello, Golang!")
}
func main() {
greet()
}
Task 2
package main
import "fmt"
func add(a, b int) int {
returna+b
}
func main() {
result := add(3, 5)
fmt.Println(result)
}
Task 3
package main
import "fmt"
func square(num int) int {
return num * num
}
func main() {
result := square(4)
fmt.Println(result)
}
Task 4
package main
import "fmt"
func sayHello(name string) {
fmt.Printf("Hello, %s!\n", name)
}
func main() {
sayHello("Alex")
}
Task 5
package main
import "fmt"
func isEven(num int) bool {
return num%2 == 0
}
func main() {
result := isEven(6)
fmt.Println(result)
}
Task 6
package main
import "fmt"
func max(a, b int) int {
ifa>b{
return a
}
return b
}
func main() {
result := max(10, 5)
fmt.Println(result)
}
Task 7
package main
import (
"fmt"
"math"
)
func getArea(radius float64) float64 {
return math.Pi * radius * radius
}
func main() {
area := getArea(5.0)
fmt.Printf("Area of circle: %.2f\n", area)
}
Task 8
package main
import "fmt"
func printNumbers(n int) {
fori:=1;i<=n;i++{
fmt.Println(i)
}
}
func main() {
printNumbers(5)
}
Task 9
package main
import "fmt"
func double(num int) int {
return num * 2
}
func main() {
result := double(3)
fmt.Println(result)
}
Task 10
package main
import "fmt"
func isPositive(num int) bool {
return num > 0
}
func main() {
result := isPositive(5)
fmt.Println(result)
}
Task 11
package main
import "fmt"
func swap(a, b int) (int, int) {
return b, a
}
func main() {
x, y := swap(3, 7)
fmt.Printf("x: %d, y: %d\n", x, y)
}
Task 12
package main
import "fmt"
func factorial(n int) int {
ifn==0{
return 1
}
result := 1
fori:=1;i<=n;i++{
result *= i
}
return result
}
func main() {
result := factorial(5)
fmt.Println(result)
}
Task 13
package main
import "fmt"
func greetUser(name string, age int) {
fmt.Printf("Hello, %s, you are %d years old!\n", name, age)
}
func main() {
greetUser("Alex", 25)
}
Task 14
package main
import "fmt"
func average(a, b float64) float64 {
return(a+b)/2
}
func main() {
result := average(10.5, 20 .5)
fmt.Printf("Average: %.2f\n", r esult)
}
Task 15
package main
import "fmt"
func isZero(num int) bool {
return num == 0
}
func main() {
result := isZero(0)
fmt.Println(result)
}
Task 16
package main
import "fmt"
func min(a, b int) int {
ifa<b{
return a
}
return b
}
func main() {
result := min(3, 7)
fmt.Println(result)
}
Task 17
package main
import "fmt"
func sumToN(n int) int {
sum:=0
fori:=1;i<=n;i++{
sum+=i
}
return sum
}
func main() {
result := sumToN(5)
fmt.Println(result)
}
Task 18
package main
import "fmt"
func convertToFahrenheit(celsius float64) float64 {
return celsius*9/5 + 32
}
func main() {
fahrenheit := convertToFahrenheit(25.0)
fmt.Printf("Temperature in Fahrenheit: %.2f\n", fahrenheit)
}
Task 19
package main
import "fmt"
func isGreaterThanTen(num int) bool {
return num > 10
}
func main() {
result := isGreaterThanTen(15)
fmt.Println(result)
}
Task 20
package main
import "fmt"
func multiply(a, b , c int) int {
returna*b*c
}
func main() {
result := multiply(2, 3, 4)
fmt.Println(result)
}
Golang Solutions: Arrays, Slices, and Maps
Task 1
package main
import "fmt"
func main() {
arr := [5]int{1, 2, 3, 4, 5}
for _, num := range arr {
fmt.Println(num)
}
}
Task 2
package main
import "fmt"
func main() {
slice := []string{"apple", "pear", "p lum"}
fmt.Println(len(slice))
}
Task 3
package main
import "fmt"
func main() {
ages := map[string]int{
"Alex": 25,
"Maria": 30,
}
fmt.Println(ages)
}
Task 4
package main
import "fmt"
func main() {
arr := [4]int{10, 20 , 30, 40}
sum:=0
for _, num := range arr {
sum += num
}
fmt.Println(sum)
}
Task 5
package main
import "fmt"
func main() {
slice := []int{1, 2, 3, 4, 5}
slice = append(slice, 6)
fmt.Println(slice)
}
Task 6
package main
import "fmt"
func main() {
days := map[string]bool{
"Monday": true,
"Tuesday": false,
}
if days["Monday"] {
fmt.Println("Monday is open")
}else{
fmt.Println("Monday is closed")
}
}
Task 7
package main
import "fmt"
func main() {
arr := [3]string{"Hello", "World", "! "}
arr[1] = "Golang"
fmt.Println(arr)
}
Task 8
package main
import "fmt"
func main() {
slice := []int{10, 20, 30, 40}
fmt.Println(slice[:2])
}
Task 9
package main
import "fmt"
func main() {
m := map[string]int{
"a": 1,
"b": 2,
}
delete(m, "a")
fmt.Println(m)
}
Task 10
package main
import "fmt"
func main() {
arr := [5]int{3, 7, 1, 9, 4}
max := arr[0]
for _, num := range arr {
ifnum>max{
max = num
}
}
fmt.Println(max)
}
Task 11
package main
import "fmt"
func main() {
slice := []int{1, 2, 3, 4, 5, 6}
slice = slice[:len(slice)-1]
fmt.Println(slice)
}
Task 12
package main
import "fmt"
func main() {
fruits := map[string]int{
"apple": 5,
"pear": 3,
}
total := 0
for _, count := range fruits {
total += count
}
fmt.Println(total)
}
Task 13
package main
import "fmt"
func main() {
arr := [3]int{1, 2, 3}
fori:=rangearr{
arr[i]++
}
fmt.Println(arr)
}
Task 14
package main
import (
"fmt"
"so rt"
)
func main() {
slice := []string{"pear", "apple", "p lum", "banana", " orange"}
sort.Strings(slice)
fmt.Println(slice)
}
Task 15
package main
import "fmt"
func main() {
m := map[string]string{
"name ": "Alex",
"color": "blue",
}
if _, exists := m["color"]; exists {
fmt.Println("Key color exists")
}else{
fmt.Println("Key color does not exist")
}
}
Task 16
package main
import "fmt"
func main() {
arr := [4]int{10, 20 , 30, 40}
sum:=0
for _, num := range arr {
sum += num
}
avg := float64(sum) / float64(len(arr))
fmt.Printf("Average: %.2f\n", a vg)
}
Task 17
package main
import "fmt"
func main() {
slice := []int{1, 2, 3}
doubled := make([]int, len(slice))
for i, num := range slice {
doubled[i] = num * 2
}
fmt.Println(doubled)
}
Task 18
package main
import "fmt"
func main() {
capitals := map[string]string{
"France": "Paris",
"Italy": "Rome",
}
fmt.Println(capitals["France"])
}
Task 19
package main
import "fmt"
func main() {
arr := [5]int{10, 20, 42, 30, 50}
found := false
for _, num := range arr {
ifnum==42{
found = true
break
}
}
fmt.Println(found)
}
Task 20
package main
import "fmt"
func main() {
slice := []int{1, 2, 3, 4}
newSlice := make([]int, len(slice))
copy(newSlice, slice)
fmt.Println(newSlice)
}
Golang Solutions: Pointers and Memory
Management
Task 1
package main
import "fmt"
func main() {
x:=42
fmt.Println(&x)
}
Task 2
package main
import "fmt"
func main() {
x:=42
ptr := &x
fmt.Println(*ptr)
}
Task 3
package main
import "fmt"
func increment(num *int) {
*num += 10
}
func main() {
x:=5
increment(&x)
fmt.Println(x)
}
Task 4
package main
import "fmt"
func main() {
str := "Hello"
ptr := &str
*ptr = "Hi"
fmt.Println(str)
}
Task 5
package main
import "fmt"
func main() {
ptr := new(float64)
*ptr = 3.14
fmt.Println(*ptr)
}
Task 6
package main
import "fmt"
func toggle(b *bool) {
*b=!*b
}
func main() {
x := true
toggle(&x)
fmt.Println(x)
}
Task 7
package main
import "fmt"
func main() {
arr := [3]int{1, 2, 3}
ptr := &arr
fmt.Println((*ptr)[0])
}
Task 8
package main
import "fmt"
func main() {
slice := []int{1, 2, 3}
ptr := &slice
*ptr = append(*ptr, 4)
fmt.Println(*ptr)
}
Task 9
package main
import "fmt"
func addEntry(m *map[string]int) {
(*m)["key"] = 42
}
func main() {
m := make(map[string]int)
addEntry(&m)
fmt.Println(m)
}
Task 10
package main
import "fmt"
func main() {
x:=42
ptr := &x
ptrToPtr := &ptr
fmt.Println(**ptrToPtr)
}
Task 11
package main
import "fmt"
func reset(num *int) {
*num=0
}
func main() {
x:=42
reset(&x)
fmt.Println(x)
}
Task 12
package main
import "fmt"
type Person struct {
Name string
}
func main() {
p := Person{Name: "Alex"}
ptr := &p
ptr.Name = "Maria"
fmt.Println(p)
}
Task 13
package main
import "fmt"
func main() {
var ptr *int
ifptr==nil{
fmt.Println("Pointer is nil")
}
}
Task 14
package main
import "fmt"
func doubleSlice(s *[]int) {
fori:=range*s{
(*s)[i] *= 2
}
}
func main() {
slice := []int{1, 2, 3}
doubleSlice(&slice)
fmt.Println(slice)
}
Task 15
package main
import "fmt"
func main() {
m := map[string]string{"a": "1" , "b": "2"}
ptr := &m
delete(*ptr, " a")
fmt.Println(*ptr)
}
Task 16
package main
import "fmt"
func swap(a, b *int) {
*a,*b=*b,*a
}
func main() {
x,y:=3,7
swap(&x, &y)
fmt.Println(x, y)
}
Task 17
package main
import "fmt"
func main() {
ptr := new(float64)
*ptr = 2.718
fmt.Println(*ptr)
}
Task 18
package main
import "fmt"
func main() {
arr := [3]int{1, 2, 3}
ptr := &arr
(*ptr)[1] = 42
fmt.Println(arr)
}
Task 19
package main
import "fmt"
type Person struct {
Age int
}
func updateAge(p *Person) {
p.Age = 30
}
func main() {
p := Person{Age: 25}
updateAge(&p)
fmt.Println(p)
}
Task 20
package main
import "fmt"
func main() {
slice := []int{1, 2, 3}
ptr := &slice
newSlice := make([]int, len(*ptr))
copy(newSlice, *ptr)
fmt.Println(newSlice)
}
Golang Solutions: Structs and Methods
Task 1
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Alex", Age: 25}
fmt.Println(p)
}
Task 2
package main
import "fmt"
type Person struct {
Name string
}
func (p Person) Greet() {
fmt.Printf("Hello, I 'm %s!\n", p .Name)
}
func main() {
p := Person{Name: "Alex"}
p.Greet()
}
Task 3
package main
import "fmt"
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func main() {
r := Rectangle{Width: 5, Height: 3}
fmt.Println(r.Area())
}
Task 4
package main
import (
"fmt"
"math"
)
type Circle struct {
Radius float64
}
func (c Circle) Perimeter() float64 {
return 2 * math.Pi * c.Radius
}
func main() {
c := Circle{Radius: 5}
fmt.Printf("Perimeter: %.2f\n", c.Perimeter())
}
Task 5
package main
import "fmt"
type Student struct {
Name string
Grade int
}
func (s Student) Pass() bool {
return s.Grade >= 60
}
func main() {
s := Student{Name: "Alex", Grade: 75}
fmt.Println(s.Pass())
}
Task 6
package main
import "fmt"
type Counter struct {
Value int
}
func (c *Counter) Increment() {
c.Value++
}
func (c *Counter) Reset() {
c.Value = 0
}
func main() {
c := Counter{}
c.Increment()
fmt.Println(c.Value)
c.Reset()
fmt.Println(c.Value)
}
Task 7
package main
import "fmt"
type Book struct {
Title string
Pages int
}
func (b Book) IsLong() bool {
return b.Pages > 300
}
func main() {
b := Book{Title: "Book", Pages: 350}
fmt.Println(b.IsLong())
}
Task 8
package main
import "fmt"
type Car struct {
Model string
Speed int
}
func (c *Car) Accelerate() {
c.Speed += 10
}
func main() {
c := Car{Model: "Toyota", Speed: 50}
c.Accelerate()
fmt.Println(c.Speed)
}
Task 9
package main
import (
"fmt"
"math"
)
type Point struct {
X, Y float64
}
func (p Point) DistanceFromOrigin() float64 {
return math.Sqrt(p.X *p.X + p.Y*p .Y)
}
func main() {
p := Point{X: 3, Y: 4}
fmt.Printf("Distance: %.2f\n", p .DistanceFromOrigin())
}
Task 10
package main
import "fmt"
type Employee struct {
Name string
Salary float64
}
func (e *Employee) IncreaseSalary(amount float64) {
e.Salary += amount
}
func main() {
e := Employee{Name: "Alex" , Salary: 50000}
e.IncreaseSalary(10000)
fmt.Println(e.Salary)
}
Task 11
package main
import "fmt"
type Box struct {
Length, Width, Height float64
}
func (b Box) Volume() float64 {
return b.Length * b.Width * b.Height
}
func main() {
b := Box{Length: 2, Width: 3, Height: 4}
fmt.Println(b.Volume())
}
Task 12
package main
import "fmt"
type Account struct {
Balance float64
}
func (a *Account) Deposit(amount float64) {
a.Balance += amount
}
func (a *Account) Withdraw(amount float64) {
if a.Balance >= amount {
a.Balance -= amo unt
}
}
func main() {
a := Account{Balance: 100}
a.Deposit(50)
a.Withdraw(30)
fmt.Println(a.Balance)
}
Task 13
package main
import "fmt"
type Triangle struct {
Base, Height float64
}
func (t Triangle) Area() float64 {
return 0.5 * t.Base * t.Height
}
func main() {
t := Triangle{Base: 6, Height: 4}
fmt.Println(t.Area())
}
Task 14
package main
import "fmt"
type User struct {
Username, Email string
}
func (u *User) UpdateEmail(newEmail string) {
u.Email = newEmail
}
func main() {
u := User{Username: "alex" , Email: "alex@example.com"}
u.UpdateEmail("new@example.com")
fmt.Println(u.Email)
}
Task 15
package main
import "fmt"
type Product struct {
Name string
Price float64
}
func (p *Product) Discount(percent float64) {
p.Price - = p.Price * (percent / 100)
}
func main() {
p := Product{Name: "Phone", Price: 1000}
p.Discount(10)
fmt.Println(p.Price)
}
Task 16
package main
import "fmt"
type Timer struct {
Seconds int
}
func (t *Timer) Start() {
t.Seconds = 60
}
func (t *Timer) Stop() {
t.Seconds = 0
}
func main() {
t := Timer{}
t.Start()
fmt.Println(t.Seconds)
t.Stop()
fmt.Println(t.Seconds)
}
Task 17
package main
import (
"fmt"
"math"
)
type Vector struct {
X, Y float64
}
func (v Vector) Magnitude() float64 {
return math.Sqrt(v.X *v.X + v.Y*v .Y)
}
func main() {
v := Vector{X: 3, Y: 4}
fmt.Printf("Magnitude: %.2f\n", v.Magnitude())
}
Task 18
package main
import "fmt"
type Library struct {
Books []string
}
func (l *Library) AddBook(book string) {
l.Books = append(l.Books, book)
}
func main() {
l := Library{}
l.AddBook("Book 1")
fmt.Println(l.Books)
}
Task 19
package main
import "fmt"
type Thermometer struct {
Temperature float64
}
func (t Thermometer) ToFahrenheit() float64 {
return t.Temperature*9/5 + 32
}
func main() {
t := Thermometer{Temperature: 25}
fmt.Printf("In Fahrenheit: %.2f\n", t .ToFahrenheit())
}
Task 20
package main
import "fmt"
type Player struct {
Name string
Score int
}
func (p *Player) AddPoints(points int) {
p.Score += points
}
func main() {
p := Player{Name: "Alex", Score: 10}
p.AddPoints(5)
fmt.Println(p.Score)
}
Golang Solutions: Interfaces and Their Usage
Task 1
package main
import "fmt"
type Speaker interface {
Speak() string
}
type Person struct {
Name string
}
func (p Person) Speak() string {
return "Hello, I am " + p.Name
}
func main() {
p := Person{Name: "Alex"}
fmt.Println(p.Speak())
}
Task 2
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
}
type Rectangle struct {
Width, Height float64
}
type Circle struct {
Radius float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
func main() {
r := Rectangle{Width: 5, Height: 3}
c := Circle{Radius: 2}
shapes := []Shape{r, c}
for _, s := range shapes {
fmt.Printf("Area: %.2f\n", s.Area())
}
}
Task 3
package main
import "fmt"
type Writer interface {
Write(string) string
}
type File struct {
Name string
}
func (f File) Write(data string) string {
return "Written to " + f.Name + ": " + data
}
func main() {
f := File{Name: "file.txt"}
fmt.Println(f.Write("data"))
}
Task 4
package main
import "fmt"
type Vehicle interface {
Move() string
}
type Car struct {
Model string
}
type Bike struct {
Model string
}
func (c Car) Move() string {
return c.Model + " moves on four wheels"
}
func (b Bike) Move() string {
return b.Model + " moves on two wheels"
}
func main() {
c := Car{Model: "Toyota"}
b := Bike{Model: "Yamaha"}
vehicles := []Vehicle{c, b}
for _, v := range vehicles {
fmt.Println(v.Move())
}
}
Task 5
package main
import "fmt"
type Counter interface {
Increment()
}
type SimpleCounter struct {
Value int
}
func (sc *SimpleCounter) Increment() {
sc.Value++
}
func main() {
sc := &SimpleCounter{}
sc.Increment()
fmt.Println(sc.Value)
}
Task 6
package main
import "fmt"
type Printable interface {
Print()
}
type Book struct {
Title string
}
type Article struct {
Title string
}
func (b Book) Print() {
fmt.Printf("Book: %s\n", b .Title)
}
func (a Article) Print() {
fmt.Printf("Article: %s\n" , a.Title)
}
func main() {
b := Book{Title: "Book 1"}
a := Article{Title: "Article 1"}
items := []Printable{b, a}
for _, item := range items {
item.Print()
}
}
Task 7
package main
import "fmt"
type Measurable interface {
Length() float64
}
type Line struct {
Start, End float64
}
func (l Line) Length() float64 {
return l.End - l.Start
}
func main() {
l := Line{Start: 2, End: 8}
fmt.Printf("Length: %.2f\n", l.Length())
}
Task 8
package main
import "fmt"
type Logger interface {
Log(string)
}
type ConsoleLogger struct {}
func (cl ConsoleLogger) Log(message string) {
fmt.Println("Log: " + message)
}
func main() {
cl := ConsoleLogger{}
cl.Log("Message")
}
Task 9
package main
import "fmt"
type Stringer interface {
String() string
}
type User struct {
Name string
}
func (u User) String() string {
return "User: " + u.Name
}
func main() {
u := User{Name: "Alex"}
fmt.Println(u.String())
}
Task 10
package main
import "fmt"
type Resizable interface {
Resize(float64)
}
type Window struct {
Size float64
}
func (w *Window) Resize(factor float64) {
w.Size *= factor
}
func main() {
w := &Window{Size: 100}
w.Resize(2)
fmt.Println(w.Size)
}
Task 11
package main
import "fmt"
type Playable interface {
Play()
}
type Song struct {
Title string
}
type Video struct {
Title string
}
func (s Song) Play() {
fmt.Printf("Playing song: %s\n" , s.Title)
}
func (v Video) Play() {
fmt.Printf("Playing video: %s\n" , v.Title)
}
func main() {
s := Song{Title: "Song 1"}
v := Video{Title: "Video 1"}
media := []Playable{s, v}
for _, m := range media {
m.Play()
}
}
Task 12
package main
import "fmt"
type Mover interface {
Move()
}
type Robot struct {
Name string
}
func (r Robot) Move() {
fmt.Printf("Robot %s is moving\n", r.Name)
}
func main() {
r := Robot{Name: "R2D2"}
r.Move()
}
Task 13
package main
import "fmt"
type Calculator interface {
Add(int, int) int
}
type BasicCalculator struct {}
func (bc BasicCalculator) Add(a, b int) int {
returna+b
}
func main() {
bc := BasicCalculator{}
fmt.Println(bc.Add(5, 3))
}
Task 14
package main
import "fmt"
type Greeter interface {
Greet() string
}
type Guest struct {
Name string
}
type Host struct {
Name string
}
func (g Guest) Greet() string {
return "Hello, I am guest " + g.Name
}
func (h Host) Greet() string {
return "Welcome, I am host " + h.Name
}
func main() {
g := Guest{Name: "Alex"}
h := Host{Name: "Maria"}
greeters := []Greeter{g, h}
for _, gr := range greeters {
fmt.Println(gr.Greet())
}
}
Task 15
package main
import (
"fmt"
"so rt"
)
type Sorter interface {
Sort()
}
type NumberSorter struct {
Numbers []int
}
func (ns *NumberSorter) Sort() {
sort.Ints(ns.Numbers)
}
func main() {
ns := &NumberSorter{Numbers: []int{5, 2, 8, 1}}
ns.Sort()
fmt.Println(ns.Numbers)
}
Task 16
package main
import "fmt"
type Reader interface {
Read() string
}
type Buffer struct {
Data string
}
func (b Buffer) Read() string {
return b.Data
}
func main() {
b := Buffer{Data: "Data"}
fmt.Println(b.Read())
}
Task 17
package main
import "fmt"
type Drawable interface {
Draw()
}
type Circle struct {
Radius float64
}
type Triangle struct {
Base float64
}
func (c Circle) Draw() {
fmt.Printf("Drawing a circle with radius %.2f\n", c.Radius)
}
func (t Triangle) Draw() {
fmt.Printf("Drawing a triangle with base %.2f\n", t.Base)
}
func main() {
c := Circle{Radius: 5}
t := Triangle{Base: 6}
shapes := []Drawable{c, t}
for _, s := range shapes {
s.Draw()
}
}
Task 18
package main
import "fmt"
type Worker interface {
Work()
}
type Employee struct {
Name string
}
func (e Employee) Work() {
fmt.Printf("%s is working\n", e .Name)
}
func main() {
e := Employee{Name: "Alex"}
e.Work()
}
Task 19
package main
import "fmt"
type Scalable interface {
Scale(float64)
}
type Image struct {
Width float64
}
func (i *Image) Scale(factor float64) {
i.Width *= factor
}
func main() {
img := &Image{Width: 100}
img.Scale(1.5)
fmt.Println(img.Width)
}
Task 20
package main
import "fmt"
type Notifier interface {
Notify()
}
type EmailNotifier struct {
Email string
}
Golang Solutions: Packages and Modules
Task 1
greeting/hello/hello.go:
package hello
func SayHello(name string) string {
return "Hello, " + name + "!"
}
main.go:
package main
import (
"fmt"
"greeting/hello"
)
func main() {
fmt.Println(hello.SayHello("Alex"))
}
Task 2
mathutils/calculator/calc.go:
package calculator
func Add(a, b int) int {
returna+b
}
func Subtract(a, b int) int {
returna-b
}
main.go:
package main
import (
"fmt"
"mathutils/calculator"
)
func main() {
fmt.Println(calculator.Add(5, 3))
fmt.Println(calculator.Subtract(5, 3))
}
Task 3
logger/log/log.go:
package log
import "fmt"
func Info(message string) {
fmt.Println("[INFO] " + message)
}
main.go:
package main
import "logger/log"
func main() {
log.Info("Message")
}
Task 4
shapes/geometry/rectangle.go:
package geometry
type Rectangle struct {
Width, Height float64
}
func Area(r Rectangle) float64 {
return r.Width * r.Height
}
main.go:
package main
import (
"fmt"
"shapes/geometry"
)
func main() {
r := geometry.Rectangle{Width: 5, Height: 3}
fmt.Println(geometry.Area(r))
}
Task 5
stringutils/reverse/reverse.go:
package reverse
func Reverse(s string) string {
runes := []rune(s)
fori,j:=0,len(runes)-1;i<j;i,j =i+1,j-1{
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
main.go:
package main
import (
"fmt"
"stringutils/reverse"
)
func main() {
fmt.Println(reverse.Reverse("Hello"))
}
Task 6
counter/increment/counter.go:
package increment
type Counter struct {
Value int
}
func (c *Counter) Inc() {
c.Value++
}
main.go:
package main
import (
"fmt"
"co unter/increment"
)
func main() {
c := &increment.Counter{}
c.Inc()
fmt.Println(c.Value)
}
Task 7
timeutils/timer/time.go:
package timer
import "time"
func Now() string {
return time.Now().String()
}
main.go:
package main
import (
"fmt"
"timeutils/timer"
)
func main() {
fmt.Println(timer.Now())
}
Task 8
formatter/text/format.go:
package text
import "strings"
func Upper(s string) string {
return strings.ToUpper(s)
}
main.go:
package main
import (
"fmt"
"formatter/text"
)
func main() {
fmt.Println(text.Upper("hello"))
}
Task 9
randomutils/dice/dice.go:
package dice
import "math/rand"
func Roll() int {
return rand.Intn(6) + 1
}
main.go:
package main
import (
"fmt"
"ra ndomutils/dice"
)
func main() {
fmt.Println(dice.Roll())
}
Task 10
validator/check/check.go:
package check
func IsPositive(n int) bool {
returnn>0
}
main.go:
package main
import (
"fmt"
"validator/check"
)
func main() {
fmt.Println(check.IsPositive(5))
}
Task 11
fileutils/reader/reader.go:
package reader
func ReadContent() string {
return "File content"
}
main.go:
package main
import (
"fmt"
"fi leutils/reader"
)
func main() {
fmt.Println(reader.ReadContent())
}
Task 12
converter/temperature/temp.go:
package temperature
func CelsiusToFahrenheit(c float64) float64 {
return c*9/5 + 32
}
main.go:
package main
import (
"fmt"
"co nverter/temperature"
)
func main() {
fmt.Println(temperature.CelsiusToFahrenheit(25))
}
Task 13
sorter/sort/sort.go:
package sort
import "sort"
func SortInts(nums []int) {
sort.Ints(nums)
}
main.go:
package main
import (
"fmt"
"so rter/sort"
)
func main() {
nums := []int{5, 2, 8, 1}
sort.SortInts(nums)
fmt.Println(nums)
}
Task 14
notifier/notify/notify.go:
package notify
import "fmt"
func Send(message string) {
fmt.Println("Notification: " + message)
}
main.go:
package main
import "notifier/notify"
func main() {
notify.Send("Message")
}
Task 15
mathops/stats/stats.go:
package stats
func Average(nums []float64) float64 {
sum := 0.0
for_, n :=rangenums{
sum+=n
}
return sum / float64(len(nums))
}
main.go:
package main
import (
"fmt"
"mathops/stats"
)
func main() {
nums := []float64{1, 2, 3, 4}
fmt.Println(stats.Average(nums))
}
Task 16
encoder/base64/encode.go:
package base64
import "encoding/base64"
func Encode(s string) string {
return base64.StdEncoding.EncodeToString([]byte(s))
}
main.go:
package main
import (
"fmt"
"en coder/base64"
)
func main() {
fmt.Println(base64.Encode("Hello"))
}
Task 17
parser/jsonparser/parser.go:
package jsonparser
func Parse(data string) string {
return "Parsed data: " + data
}
main.go:
package main
import (
"fmt"
"parser/jsonparser"
)
func main() {
fmt.Println(jsonparser.Parse("{\"key\": \"value\"}"))
}
Task 18
auth/user/auth.go:
package user
type User struct {
Name string
}
func Authenticate(u User) string {
return "Authentication successful for " + u.Name
}
main.go:
package main
import (
"fmt"
"auth/user"
)
func main() {
u := user .User{Name: "Alex"}
fmt.Println(user.Authenticate(u))
}
Task 19
generator/uuid/uuid.go:
package uuid
func Generate() string {
return "550e8400-e29b-41d4-a716-446655440000"
}
main.go:
package main
import (
"fmt"
"generator/uuid"
)
func main() {
fmt.Println(uuid.Generate())
}
Task 20
cache/memory/cache.go:
package memory
type Cache
Golang Solutions: Error Handling
Task 1
package main
import (
"error s"
"fmt"
)
func Divide(a, b float64) (float64, error) {
ifb==0{
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
result, err := Divide(10, 0)
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
}
Task 2
package main
import (
"error s"
"fmt"
"strconv"
)
func ParseInt(s string) (int, error) {
num, err := strconv.Atoi(s)
iferr!=nil{
return 0, errors.New("invalid string")
}
return num, nil
}
func main() {
num, err := ParseInt("abc")
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Number:", num)
}
Task 3
package main
import (
"error s"
"fmt"
)
func FindElement(slice []int, target int) (int, error) {
for i, v := range slice {
ifv==target{
return i, nil
}
}
return -1, errors .New("element not found")
}
func main() {
slice := []int{1, 2, 3, 4}
idx, err := FindElement(slice, 5)
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Index:", i dx)
}
Task 4
package main
import (
"error s"
"fmt"
)
type User struct {
ID int
Name string
}
func GetUser(id int) (User, error) {
ifid!=1{
return User{}, errors.New("user not found")
}
return User{ID: id, Name: "Alex"}, nil
}
func main() {
user, err := GetUser(2)
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("User:", us er)
}
Task 5
package main
import (
"error s"
"fmt"
)
func CheckPositive(n int) error {
ifn<=0{
return errors.New("number must be positive")
}
return nil
}
func main() {
err := CheckPositive(-5)
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Number is valid")
}
Task 6
package main
import (
"error s"
"fmt"
)
func ReadConfig() (string, error) {
return "", e rrors .New("failed to read config")
}
func main() {
config, err := ReadConfig()
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Config:", config)
}
Task 7
package main
import (
"error s"
"fmt"
"strings"
)
func ValidateEmail(email string) error {
if !strings.Contains(email, " @") {
return errors.New("invalid email")
}
return nil
}
func main() {
err := ValidateEmail("invalid")
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Email is valid")
}
Task 8
package main
import (
"error s"
"fmt"
)
func OpenFile(filename string) (string, error) {
if filename != "valid.txt" {
return "", er rors.New("file does not exist")
}
return "file content", nil
}
func main() {
content, err := OpenFile("invalid.txt")
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Content:", content)
}
Task 9
package main
import (
"error s"
"fmt"
"math"
)
func CalculateSquareRoot(n float64) (float64, error) {
ifn<0{
return 0, errors.New("negative number")
}
return math.Sqrt(n), nil
}
func main() {
result, err := CalculateSquareRoot(-4)
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
}
Task 10
package main
import (
"error s"
"fmt"
)
func CheckLength(s string) error {
iflen(s)==0{
return errors.New("string is empty")
}
return nil
}
func main() {
err := CheckLength("")
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("String is valid")
}
Task 11
package main
import (
"error s"
"fmt"
)
func ConnectDB() (string, error) {
return "", e rrors .New("failed to connect to database")
}
func main() {
conn, err := ConnectDB()
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Connection:", co nn)
}
Task 12
package main
import (
"error s"
"fmt"
"time"
)
func ParseDate(date string) (time.Time, error) {
t, err := time.Parse("2006-01 -02", date)
iferr!=nil{
return time.Time{}, errors.New("invalid date format")
}
return t, nil
}
func main() {
date, err := ParseDate("2023-13-01")
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Date:", date)
}
Task 13
package main
import (
"error s"
"fmt"
)
func CheckAge(age int) error {
ifage<18{
return errors.New("age must be at least 18")
}
return nil
}
func main() {
err := CheckAge(16)
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Age is valid")
}
Task 14
package main
import (
"error s"
"fmt"
)
func FetchData() (string, error) {
return "", e rrors .New("failed to fetch data")
}
func main() {
data, err := FetchData()
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Data:", data)
}
Task 15
package main
import (
"error s"
"fmt"
"strconv"
)
func ConvertToFloat(s string) (float64, error) {
f, err := strconv.ParseFloat(s, 64)
iferr!=nil{
return 0, errors.New("invalid number")
}
return f, nil
}
func main() {
num, err := ConvertToFloat("abc")
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Number:", num)
}
Task 16
package main
import (
"error s"
"fmt"
)
func CheckSlice(slice []int) error {
if len(slice) == 0 {
return errors.New("slice is empty")
}
return nil
}
func main() {
slice := []int{}
err := CheckSlice(slice)
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Slice is valid")
}
Task 17
package main
import (
"error s"
"fmt"
)
func SendRequest() (string, error) {
return "", e rrors .New("failed to send request")
}
func main() {
response, err := SendRequest()
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Response:" , response)
}
Task 18
package main
import (
"error s"
"fmt"
)
func ValidatePassword(password string) error {
if len(password) < 8 {
return errors.New("password must be at least 8 characters")
}
return nil
}
func main() {
err := ValidatePassword("pass")
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Password is valid")
}
Task 19
package main
import (
"error s"
"fmt"
)
func CheckEven(n int) error {
ifn%2!=0{
return errors.New("number must be even")
}
return nil
}
func main() {
err := CheckEven(3)
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Number is valid")
}
Task 20
package main
import (
"error s"
"fmt"
)
func ProcessData() (string, error) {
return "", e rrors .New("failed to process data")
}
func main() {
result, err := ProcessData()
iferr!=nil{
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
}