CodeBlanks Logo Icon CodeBlanks

Declaration with var

Learn to declare variables with the var keyword.

Declaration with var

The most basic way to declare a variable in Go is the var keyword. Writing var name int creates an integer variable named name and Go initialises it with its zero value.

You can state the type explicitly or, when you give an initial value, let Go infer it: var x = 5. Variables declared with var can live at package or function scope.

Without an initial value, numeric types become 0, string "", bool false. This reduces unexpected bugs.

var syntax

var has two forms. First, explicit type: var x int. Second, with value: var x = 10. In the second, Go infers the type from the right side.

You can declare several variables in one line: var a, b int. Even var a, b = 1, 2 with different types is possible.

Package-level var declarations are visible across the file. Inside a function, only that function sees them.

Practice Declare with var

Declare three variables with var: explicit type var ad string = "Ada", inferred from value var yas = 36, and without a value var aktif bool. Print all three with one fmt.Println.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    var ad string = "Ada"
    var yas = 36
    var aktif bool
    fmt.Println(ad, yas, aktif)
}

Expected output

Ada 36 false

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the initial value of x in var x int?

  • 0 Correct answer
  • nil
  • 1
  • undefined

Explanation: The zero value of int is 0.

2 Variable declaration

Question
To declare an int named x:
____ x int
Answer
To declare an int named x:
var x int

Explanation: the var keyword declares a variable.

3 Match the declarations

Term Meaning
var x int Explicit type
var x = 5 Type inference
var a, b int Multiple
var x string Text

All lessons in Beginner