Skip to main content

Command Palette

Search for a command to run...

Variables in Go

Updated
2 min read

Variables in go can be declared using following syntax

var <variable-name> <data-type> = <value>

For e.g.

package main

func main(){
    var x int = 40
}

There is also a shortcut of defining variables

package main

func main(){
    x := 10
}

In the above case, we have used the := operator which is the shortcut method to declare variables. You don’t need to write var neither do you need to write the type. The type is inferred from the value. Basically whatever value is, the type is assigned accordingly.

package main

import (
    "reflect"
    "fmt"
)

func main(){
    x := 10
    y := "I am a string"
    fmt.Println(reflect.TypeOf(x), reflect.TypeOf(y))
}

In the above example, we have imported the reflect package which is a standard built-in package for go. Using reflect, we can determine the type of x and y. You will notice x will be int and y will be string.

Defining Variables in Bulk

package main
import "fmt"
func main(){
    var (    
        c = 10
        d = 20
        e = 30
    )
    fmt.Println(c, d, e)
    var (
        f int
        g int
        h int
    )
    fmt.Println(f, g, h)
    var i, j, k int
    i = 1
    j = 2
    k = 3
    fmt.Println(i, j, k)
    var l, m, n int = 4, 5, 6
    fmt.Println(l, m, n)
    o, p, q := 1, 2, 3
    fmt.Println(o, p, q)
}

In the above example, we are declaring and initializing variable c, d, e at once. We are declaring f, g, h and initializing them later. Similarly we are declaring i, j, k once with combining their types, basically all three will have same int type. Then we are declaring and initializing l, m, n at once. At the end, we are using shortcut method to declare o, p, q. These are different ways to define variables.

Constants

Go supports constants

const x int = 5

Constants cannot be defined using := and they need const keyword.

Go Programming Language - Basic To Advance

Part 3 of 5

This series is all about Go Programming Language. We will start from basic features and then discuss about creating large projects with best practices and at the end also cover system design and design patterns using Golang.

Up next

Hello World in Go

Go can be downloaded through the official website; click here. Once you have installed Go, to check if go has been correctly installed, you can open a terminal and write below comand. go version This should show you current version of Go. Next. Crea...

More from this blog

P

Programming, System Design and AI | Latencot

15 posts

Hear, you will read all about tech and tech updates. From writing code to building AI systems, we'll talk and share about everything.