Exercise 2: Variables and Types in Go

In this exercise, you'll learn how to declare and use variables in Go.

Before You Start: Check Your Go Installation

If you already installed Go in the first exercise, you can skip this step.

If not, follow this guide to install Go on your machine: Install Go

Instructions:

  • 1️⃣ Create a new file in your Go project, named variables.go.
  • 2️⃣ Declare and initialize multiple variables of different types (int, string, bool).
  • 3️⃣ Print their values using the fmt.Println() function.

🚀 Once your editor is ready, start coding! 😃

package main

import "fmt"

func main() {
    var x int = 10
    var y string = "Hello, Go!"
    var z bool = true

    fmt.Println("Value of x:", x)
    fmt.Println("Value of y:", y)
    fmt.Println("Value of z:", z)
}
  • 4️⃣ Run the program using the command: go run variables.go

Code Explanation:

1️⃣ var x int = 10 : Declares a variable x of type integer (int) and assigns it the value 10.

2️⃣ var y string = "Hello, Go!" : Declares a variable y of type string and assigns it the message "Hello, Go!".

3️⃣ var z bool = true : Declares a variable z of type boolean (bool) and assigns it the value true.

4️⃣ fmt.Println() : Prints the value of each variable to the console.

✅ If your program is correct, running it should display the following values in the console:

Value of x: 10

Value of y: Hello, Go!

Value of z: true

← Previous Exercise Next Exercise →

🚀 Thanks for using these exercises! If you find this content helpful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊


☕ Buy me a coffee