Go > Variables and Constants > Declaration and Initialization > Var keyword

Declaring and Initializing Variables with 'var'

Learn how to declare and initialize variables in Go using the var keyword. This example demonstrates different ways to declare variables, including explicit type declaration and type inference.

Basic Variable Declaration and Initialization

This code demonstrates the most basic way to declare and initialize variables in Go using the var keyword. You explicitly specify the variable name, its type (e.g., int, string, bool), and its initial value. The fmt.Println function is then used to print the values of these variables to the console.

package main

import "fmt"

func main() {
	// Declare a variable of type int and initialize it with a value.
	var age int = 30
	fmt.Println("Age:", age)

	// Declare a variable of type string and initialize it with a value.
	var name string = "Alice"
	fmt.Println("Name:", name)

	// Declare a variable of type bool and initialize it with a value.
	var isStudent bool = false
	fmt.Println("Is Student:", isStudent)
}

Type Inference with 'var'

Go supports type inference with the var keyword. If you provide an initial value, Go can automatically determine the type of the variable. In this example, quantity is inferred to be an int, price is inferred to be a float64, and message is inferred to be a string based on the values assigned during initialization. This makes the code more concise while maintaining type safety.

package main

import "fmt"

func main() {
	// Declare and initialize a variable. The type is inferred from the value.
	var quantity = 10 // Type is inferred as int
	fmt.Println("Quantity:", quantity)

	var price = 99.99 // Type is inferred as float64
	fmt.Println("Price:", price)

	var message = "Hello, Go!" // Type is inferred as string
	fmt.Println("Message:", message)
}

Multiple Variable Declaration

You can declare multiple variables of the same type on a single line using the var keyword. You can also declare and initialize multiple variables of different types on a single line, taking advantage of type inference. In this example, x, y, and z are declared as integers, and then assigned values separately. a, b, and c are declared and initialized in one line with types inferred as int, string, and bool respectively.

package main

import "fmt"

func main() {
	// Declare multiple variables of the same type.
	var x, y, z int
	x = 10
	y = 20
	z = 30
	fmt.Println("x:", x, "y:", y, "z:", z)

	// Declare and initialize multiple variables of different types in one line.
	var a, b, c = 1, "Hello", true
	fmt.Println("a:", a, "b:", b, "c:", c)
}

Concepts Behind the Snippet

The var keyword is fundamental to variable declaration in Go. It allows you to create named storage locations in memory to hold data. Go is a statically typed language, meaning that the type of a variable is known at compile time. Using var with explicit type declaration ensures type safety. Type inference allows for more concise code while still maintaining type safety.

Real-Life Use Case

Consider a scenario where you are building a web application. You might use variables to store user input, such as a username (string) or an age (int). The var keyword allows you to declare these variables and initialize them with default values or values obtained from user input or database queries. For example, you might declare var username string and then later assign it the value entered by the user.

Best Practices

  • Use explicit type declaration with var when the type is not immediately obvious from the initial value. This improves code readability.
  • Leverage type inference with var when the type is clear from the initial value, especially in short functions where context is readily available.
  • Choose meaningful variable names that clearly indicate the purpose of the variable.
  • Initialize variables at the point of declaration whenever possible.

Interview Tip

Be prepared to discuss the differences between var and short variable declaration (:=). The var keyword is used for declaring variables at package or function level, and can declare a variable without initialization. The short variable declaration := is used only inside functions, and it both declares and initializes a variable. Also, be ready to explain the concept of type inference and its benefits.

When to Use 'var'

Use the var keyword when:

  • You want to declare a variable without immediately initializing it.
  • You want to declare a variable at the package level (outside of a function).
  • You want to explicitly specify the type of a variable.

Memory Footprint

The memory footprint of a variable declared with var depends on its type. For example, an int typically occupies 4 or 8 bytes of memory, a string occupies memory for its header and the underlying character data, and a bool typically occupies 1 byte. Understanding the memory footprint of different types is important for optimizing memory usage in your Go programs.

Alternatives

The primary alternative to var within a function is the short variable declaration operator (:=). This operator combines declaration and initialization in a single statement and infers the variable type. However, it can only be used inside functions and requires an initial value. Constants are declared using the const keyword.

Pros of using 'var'

  • Explicit type declaration enhances code readability.
  • Can be used to declare variables without immediate initialization.
  • Usable at both package and function level scope.

Cons of using 'var'

  • More verbose than short variable declaration (:=) when used inside functions with initialization.
  • Can sometimes lead to redundant code if the type is obvious from the initialization value and explicit type declaration is used unnecessarily.

FAQ

  • What is the difference between var and := in Go?

    var is used for declaring variables, with or without initialization, and can be used at both package and function level scope. := is a short variable declaration operator that combines declaration and initialization in a single statement. It can only be used inside functions.
  • Can I declare a variable with var without initializing it?

    Yes, you can declare a variable with var without initializing it. The variable will then have its zero value. For example, var x int will declare an integer variable x with a value of 0.
  • What is type inference in Go?

    Type inference is the ability of the Go compiler to automatically deduce the type of a variable based on its initial value. This simplifies code and reduces verbosity. For example, var message = "Hello" will infer that message is of type string.