Go is a programming language designed for simplicity and efficiency. Let's start by writing your first program: "Hello, World!"
Learn more about Go basics
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
- Change the message to say "Hello, [Your Name]!"
- Add another line that says "I am learning Go!"
Go has several basic data types: string
, int
, float64
, and bool
.
Learn more about Go data types
package main
import "fmt"
func main() {
var name string = "Alice"
var age int = 11
var height float64 = 4.5
var isLearning bool = true
fmt.Println("Name:", name)
fmt.Println("Age:", age)
fmt.Println("Height:", height)
fmt.Println("Is Learning Go:", isLearning)
}
- Change the values of the variables to describe yourself.
- Add a new variable for your favorite color and print it.
- Try declaring a variable without specifying its type.
If statements allow your program to make decisions.
Learn more about if statements
package main
import "fmt"
func main() {
age := 11
if age < 13 {
fmt.Println("You are a child.")
} else {
fmt.Println("You are a teenager or older.")
}
}
- Add a condition to check if age is between 13 and 19
- Add a condituon to check if age is above 19
- Add a condition to check if age is below 13
- Add a conditon to check whether or not the age is even or odd
Command-line arguments allow you to pass information to your program when you run it.
Learn more about command-line arguments
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage: go run main.go [your name]")
return
}
name := os.Args[1]
fmt.Printf("Hello, %s!\n", name)
fmt.Println("I am learning Go!")
}
- Modify the program to accept a second argument for your age and print it.
- Add a condition to check if no arguments are provided and display a helpful message.
- Experiment with passing multiple arguments and printing them all.
Functions are reusable blocks of code. They help organize your program.
Learn more about functions
package main
import "fmt"
func greet(name string) {
fmt.Println("Hello,", name)
}
func main() {
greet("Alice")
}
- Modify the
greet
function to include the person's age. - Write a new function that adds two numbers and prints the result.
- Call your new function in the
main
function.
Switch statements allow you to simplify multiple conditional checks.
Learn more about switch statements
package main
import "fmt"
func main() {
day := "Monday"
switch day {
case "Monday":
fmt.Println("Start of the work week.")
case "Friday":
fmt.Println("Almost the weekend!")
case "Saturday", "Sunday":
fmt.Println("It's the weekend!")
default:
fmt.Println("It's a regular weekday.")
}
}
- Modify the program to include a case for your favorite day of the week.
- Add a case that checks for multiple days (e.g., "Tuesday" and "Thursday").
- Write a program that uses a switch statement to categorize a number as positive, negative, or zero.
Loops let you repeat actions in your program.
Learn more about loops
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
fmt.Println("Count:", i)
}
}
- Write a loop that prints numbers from 10 to 1.
- Create a loop that prints all even numbers between 1 and 20.
- Use a
while
-like loop (afor
loop with a condition) to keep asking for input until the user types "stop".
Tests ensure your code works as expected.
Learn more about testing
package main
func add(a, b int) int {
return a + b
}
Test File:
package main
import "testing"
func TestAdd(t *testing.T) {
result := add(2, 3)
if result != 5 {
t.Errorf("Expected 5, got %d", result)
}
}
- Write a test for a function that multiplies two numbers.
- Add a test for a function that checks if a number is even.
- Run your tests and fix any errors.
Create a command-line calculator that:
- Asks the user for two numbers.
- Asks the user for an operation (+, -, *, /).
- Performs the operation and prints the result.
- Repeats until the user types "exit".
Go does not have classes, but you can use structs and methods to achieve similar functionality.
Learn more about structs and methods
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (p Person) Greet() {
fmt.Printf("Hello, my name is %s and I am %d years old.\n", p.Name, p.Age)
}
func main() {
person := Person{Name: "Alice", Age: 11}
person.Greet()
}
- Add a new field to the
Person
struct for the person's favorite hobby. - Write a method that prints the person's hobby.
- Create multiple
Person
instances and call their methods.
Go provides tools to work with files for reading and writing data.
Learn more about file handling
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Create("example.txt")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close()
file.WriteString("Hello, Go!")
fmt.Println("File written successfully.")
}
- Modify the program to read the content of the file and print it.
- Write a program that appends text to an existing file.
- Handle errors gracefully when the file does not exist.
Go makes it easy to create web servers using the net/http
package.
Learn more about web servers
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome to my web server!")
}
func main() {
http.HandleFunc("/", handler)
fmt.Println("Starting server on :8080...")
http.ListenAndServe(":8080", nil)
}
- Modify the handler to display a personalized message based on a query parameter (e.g.,
?name=Alice
). - Add a new route that displays the current date and time.
- Create a simple HTML page and serve it using your web server.
You can serve HTML and CSS files to create more interactive web pages.
Learn more about serving files
package main
import (
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("./static"))
http.Handle("/", fs)
http.ListenAndServe(":8080", nil)
}
- Create a
static
folder with anindex.html
file and serve it. - Add a CSS file to style your HTML page.
- Create a form in your HTML page and handle its submission in Go.
Interfaces define a set of methods that a type must implement.
Learn more about interfaces
package main
import "fmt"
type Shape interface {
Area() float64
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
func main() {
var s Shape = Circle{Radius: 5}
fmt.Println("Area of the circle:", s.Area())
}
- Create a
Rectangle
struct and implement theShape
interface. - Write a function that takes a
Shape
and prints its area. - Add another method to the
Shape
interface and implement it for bothCircle
andRectangle
.