Sobes.tech
Junior

What are the differences between fast variable declaration and declaration using the var keyword?

sobes.tech AI

Answer from AI

  • Short variable declaration (:=) is used only inside functions. It declares and initializes one or more variables. The variable type is automatically determined based on the type of the value assigned to it.

  • Declaration with var can be used both inside and outside functions.

    • Inside functions, it allows declaring a variable without immediate initialization (it gets the zero value for its type) or with initialization. The type can be explicitly specified.
    • Outside functions, var is used to declare package-level variables. Here, either an explicit type or initialization is required.

Example:

package main

import "fmt"

var globalVar int // Declaration at package level, zero value = 0

func main() {
	// Short declaration inside function
	localVar := "Hello" // Type is automatically determined (string)
	anotherVar := 123     // Type is automatically determined (int)

	fmt.Println(localVar, anotherVar)

	// Declaration with var inside function
	var i int      // Declaration without initialization, i = 0
	var j string   // Declaration without initialization, j = ""
	var k float64 = 3.14 // Declaration with explicit type and initialization

	fmt.Println(i, j, k)

	// Using globalVar
	globalVar = 100
	fmt.Println(globalVar)
}