How to declare and initialize variables in Golang or Go?

Published July 15, 2022

To declare and initialize variables in Golang or Go, there are 2 ways to do it:

Declare and initialize the variables at the same time using the := operator - The short way

To declare and initialize the variable at the same, we can write the name of the variable followed by the := operator and then the value for the variable.

Golang compiler will automatically infer or analyze the type using the value assigned.

It can be done like this,

package main

// Method:
// Declare and initialize the variables at the
// same time using the `:=` operator - The short way

import "fmt"

func main() {
    // declare and initialize the
    // varaible using the `:=` operator
    name := "John Doe"

    // log to the console
    fmt.Print(name)
}

See the above code live in The Go Playground.

We have successfully declared and initialized the variable at the same time. Yay 🥳!

Declare variable first and initialize it later

To declare the variable first we can use the var keyword followed by the name of the variable and then its type. And to initialize the variable with a value you can use the variable name followed by the = operator (assignment operator symbol) and then the value you need to assign to the variable.

TL;DR

package main

// Method:
// Declare variable first and initialize it later - The long way

import "fmt"

func main() {
    // declare variable and its type
    // using the `var` keyowrd
    var name string

    // assign a string value to
    // it using the `=` operator
    name = "John Doe"

    // log to the console
    fmt.Print(name)
}

For example, let's say we need to make a variable called name with the type of string.

It can be done like this,

package main

func main()  {
    // declare variable and its type
    // using the `var` keyowrd
    var name string
}

Now to initialize it with a value let's use the = operator (assignment operator) and then type the value it needs to hold.

It can be done like this,

package main

// Method:
// Declare variable first and initialize it later - The long way

import "fmt"

func main() {
    // declare variable and its type
    // using the `var` keyowrd
    var name string

    // assign a string value to
    // it using the `=` operator
    name = "John Doe"

    // log to the console
    fmt.Print(name)
}

See the above code live in The Go Playground.

We have successfully declared and then initialized the variable in Golang 😃.

That's all 😃!

Feel free to share if you found this helpful 😃.


Share on: Facebook Twitter