Skip to main content

Variables in Go

Published 2 min readMarkdown
Part of seriesGo Programming Language - Basic To Advance

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.

No comments yet. Be the first to comment.

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 nextPrimitive Data Types in GoUnlike languages like Python and Javascript, Go is statically typed. That means once a variable type is defined, the variable will only store that type of data. Go has 3 basic types bool Numeric string Bool To declare a variable and then initali...

More from this blog