Declare Variables

Declaring Variables #

In Go, there are two primary ways to declare a variable:


✅ 1. Using the var Keyword #

Declare a variable using the var keyword, followed by the variable name, type, and optionally an initial value.

Syntax: #

var variableName type = value

💡 Note: You must specify either the type, the value, or both.

Example: #

package main

import "fmt"

func main() {
    var student1 string = "John"
    var student2 = "Jane"  // Type is inferred automatically

    fmt.Println(student1)
    fmt.Println(student2)
}

✅ 2. Using the := Shorthand #

Declare and initialize a variable in one line using :=. The compiler automatically infers the variable’s type based on the value.

Syntax: #

variableName := value

👉 Important: This shorthand can only be used inside functions and must include an initial value.

Example: #

package main

import "fmt"

func main() {
    x := 2
    message := "Hello Go"

    fmt.Println(x)
    fmt.Println(message)
}

✅ Variable Declaration Without Initial Value #

If you declare a variable without assigning an initial value, Go automatically assigns a default value based on the type.

Example: #

package main

import "fmt"

func main() {
    var a string
    var b int
    var c bool

    fmt.Println(a)  // Output: ""
    fmt.Println(b)  // Output: 0
    fmt.Println(c)  // Output: false
}

✅ Assign Value After Declaration #

You can declare a variable first and assign its value later.

Example: #

package main

import "fmt"

func main() {
    var student1 string
    student1 = "John"

    fmt.Println(student1)
}

👉 Note: Using := without assigning a value is not allowed.


✅ Difference Between var and := #

Featurevar:=
ScopeCan be used inside and outside functionsOnly inside functions
Declaration + InitializationCan be separateMust be done in the same line
Examplevar a int = 1a := 1

Example of var Outside Function: #

package main

import "fmt"

var a int
var b int = 2
var c = 3

func main() {
    a = 1
    fmt.Println(a, b, c)
}

Example of := Outside Function (Error): #

package main

import "fmt"

a := 1  // ❌ Syntax error

func main() {
    fmt.Println(a)
}

Result:

./prog.go:5:1: syntax error: non-declaration statement outside function body

🚀 By understanding these methods, you’ll have a solid foundation for variable management in Go. Explore more about declaring multiple variables and naming rules next.