Menu
Coddy logo textTech

Initializing Variables

Part of the Fundamentals section of Coddy's GO journey — lesson 38 of 109.

Let's learn how to initialize variables in Go. Initializing means giving a variable a starting value when you create it.

First, let's see how to initialize variables using the var keyword:

var age int = 25
var name string = "Gopher"
var isActive bool = true
    
fmt.Println(age, name, isActive)

After executing this code, the values of our variables will show on the screen:

25 Gopher true

We can also use Go's short declaration operator (:=) to make our code more concise:

age := 25
name := "Gopher"
isActive := true
    
fmt.Println(age, name, isActive)

After executing this code, we get the same result as before:

25 Gopher true

The short declaration operator (:=) automatically figures out the type based on the value you provide, which makes your code cleaner and easier to read.

challenge icon

Challenge

Beginner

In this challenge, you'll practice initializing variables in Go. Your task is to initialize three variables with specific values and then print them.

The program already has the variable declarations, but you need to initialize them with the following exact values:

  • name — a string set to "John"
  • age — an int set to 25
  • isStudent — a bool set to true

The expected output is:

Name: John
Age: 25
Is Student: true

Cheat sheet

Initialize variables in Go using the var keyword:

var age int = 25
var name string = "Gopher"
var isActive bool = true

Use the short declaration operator (:=) for more concise code:

age := 25
name := "Gopher"
isActive := true

The short declaration operator automatically determines the variable type based on the assigned value.

Try it yourself

package main

import "fmt"

func main() {
    // TODO: Initialize these variables with the required values
    var name string    // Initialize with "John"
    var age int       // Initialize with 25
    var isStudent bool // Initialize with true
    
    // This code will print the variables
    fmt.Println("Name:", name)
    fmt.Println("Age:", age)
    fmt.Println("Is Student:", isStudent)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals