go-tutorial

Go Variables and Constants

Variables are used to store values in the Go programming language. They are labels that are applied to values. The var keyword in Go is used to declare a list of variables. To declare variables, we may also utilise the:= shorthand syntax.

Variables can hold a variety of data kinds. A data type is a collection of values and the actions that can be performed on them. In many circumstances, Go can deduce the data type from the assignment’s right side.

Variables’ stored values can vary over time. Constants, on the other hand, maintain their values after they have been defined.

Go declare variables

The type of the variable follows the variable name.

package main

import "fmt"

func main() {

    var i int = 1
    var w float64 = 12.5

    fmt.Println(i, w)
}

In the code example, we declare and initialize two variables. Later, we print them.

1 12.5

Go declare multiple variables

With the var keyword, we can declare multiple variables at once.

package main

import (
    "fmt"
)

func main() {

    var i, j, k = 1, 2, 3

    var (
        name     = "Learn Code Zone"
        language = "Go"
    )

    fmt.Println(i, j, k)
    fmt.Printf("%s teaches %s\n", name, language)
}

The example shows how to declare multiple variables with var.

1 2 3
Learn Code Zone teaches Go

Declaration without initialization

Declaring variables begins with the keyword var, followed by the desired name and the type of value the variable will retain.

package main

import "fmt"

func main() {
	var i int
	var s string

	i = 10
	s = "Learn Code Zone"

	fmt.Println(i)
	fmt.Println(s)
}

Following the execution of the preceding instructions, the variable I will be set to 10 and the variable s will be set to Learn Code Zone.

Output

10
Learn Code Zone

Declaration with type inference

When assigning a value to a variable at the time of declaration, you can omit the variable type from the declaration. The type of the variable will be determined by the type of the value assigned to it.

package main

import (
	"fmt"
	"reflect"
)

func main() {
	var i = 10
	var s = "Learn Code Zone"

	fmt.Println(reflect.TypeOf(i))
	fmt.Println(reflect.TypeOf(s))
}

Output

int
string

Variable Naming Conventions in Golang

The following are the rules for naming a Golang variable:

  • A name must begin with a letter and can have any number of letters and numbers after that.
  • A number cannot be the first character in a variable name.
  • There can’t be any spaces in the name of a variable.
  • If a variable’s name starts with a lower-case letter, it is regarded an unexported variable because it can only be accessed within the current package.
  • If a variable’s name starts with a capital letter, it is considered an exported variable because it can be accessed from packages other than the present one.
  • If a name has more than one word, each one following the first should be capitalised, as in empName, EmpAddress, and so on.
  • Variable names are case-sensitive (car, Car and CAR are three different variables).

Golang Constants

A constant value is declared via the const keyword. Constant expressions allow for arbitrary precision in arithmetic. Until the type is specified, such as by an explicit cast, the numeric constant has no type.

When a number is used in a context that demands it, such as a variable assignment or a function call, it is given the type.

We use the term constant in Golang to indicate fixed (unchanging) numbers such as 3.14, 21, “Hello,” and so on.

Literals are unchanging. All literals in Go are constants, whether they be integer literals such as 21, 46, floating-point literals such as 3.14, 19.21, boolean literals such as true, false, or string literals such as “Krunal,” “Ankit.”

Declaring a Constant in Golang

We can declare a constant and give it a name, and you can use the keyword const like the following.

const blog = "LearnCodeZone"
const flag = true

You can also specify the type in the declaration like the following code.

const x int = 2022
const y string = "Abhinav"

We can also define multiple constants. See the following code.

package main

import "fmt"

func main() {
    const name, country = "Abhinav", "India"

    const (
        stockName  string  = "LearnCodeZone"
        stockPrice float64 = 700.00
    )
    fmt.Println(stockName, stockPrice)
        fmt.Println(name, country)
}

See the below output.

LearnCodeZone 700
Abhinav India

Now, let’s try to modify the value of the constants and see the result.

package main

import "fmt"

func main() {
    const name, country = "Abhinav", "India"
    name = "Niraj"
    fmt.Println(name, country)
}

See the below output.

./prog.go:7:2: cannot assign to name (untyped string constant "Abhinav")
Go build failed.

So, we have got the error like Cannot assign the constant.

Example

package main

import "fmt"

const PRODUCT string = "Book"
const PRICE = 500

func main() {
	fmt.Println(PRODUCT)
	fmt.Println(PRICE)
}

You can also omit the type at the time the constant is declared. The type of the value assigned to the constant will be used as the type of that variable.

Output

Book
500

Multilple Constants Declaration Block

For better readability and code quality, constant declarations can be clustered together into blocks.

package main

import "fmt"

const (
	PRODUCT  = "Mobile"
	QUANTITY = 50
	PRICE    = 50.50
	STOCK  = true
)

func main() {
	fmt.Println(QUANTITY)
	fmt.Println(PRICE)
	fmt.Println(PRODUCT)
	fmt.Println(STOCK)
}


Output

50
50.5
Mobile
true

Golang Constant Naming Conventions

  • Constant names must follow the same requirements as variable names, which means they must begin with a letter or underscore and include any number of characters, digits, or underscores.
  • Constant names are frequently written in uppercase letters as a matter of convention. This is so that they can be easily distinguished from variables in the source code.

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.