Saturday, April 10, 2021

Golang - Variables

Variables



A variable is similar to a storage box in which a value is stored.

It has a name that we can use to get the value. (It might be unnamed, such as slice.)

Variables in Go are static types, which means they cannot be changed once defined.

Variable values can be modified, but they must be of the same type as the existing ones.

At runtime, the value will be allocated in computer memory.


Basic Data Types



* int 
    -1 0 1

* float64 
    -.1 0 1.
    -0.1 0.0 1.0

* bool
    true false

* string
    "Hello World"    <= Unicode


Declarations



Variable must be declared before it can be used.

Otherwise, you will receive an error similar to the one shown below.


fmt.Println(height)


Error:

   undefined: height



Furthermore, we must use the 'syntax' format below to declare variables.


* Format *
    var height int



More Details:

* var:        short for variable
* 'height':   name of the variable (also called identifier)
* int:        static type of the variable (It is 'int 0' as default type and value)

In Go, the name must begin with a letter (any Unicode character would suffice) or an underscore.
In addition, every variable and value in Go has a type.


Zero Values



Before assigning value to variables, Go will help us to setup the initial value (or called Zero Value) depending on its type.

Why does Go do that for us?

Because variables will point to PC memory addresses, if there is already data there, the logic of our program will be broken.

Consider declaring an int variable whose default value is determined by what is in memory (it may be a random number such as 1, 4, or 100).

The values of variables are then unpredictable. Go will set the initial value for us to avoid receiving garbage values in pointed memory.

Below is the zero value for each type:

    int                  0

    float64           0.0

    bool               false

    string             ""

    pointer           nil (which mean it does not point to memory address)


Blank Identifier



In Go, it is usual for a method to return two values: one computed value and one error.

exp/main.go

func getValueAndError() (intbool) {
    return 1false
}

func main() {
     valueerr := getValueAndError()
    if err {
         fmt.Println("Pass")
    }
}


Some responses may or may not be used in our program.
The compiler will then generate an error.

Error:

   value declared and not used


The reason for this is because Go will assist us in creating a maintainable program by eliminating extraneous code (improve readability).

In any case, how can we avoid this error message? We can utilize the 'Blank Identifier' function given by Go. 

We can modify the example as follows:


// If we don't care the return value, then we can use '_' to discard it
_err := getValueAndError()

 

Declare multiple variables



If they are the same type, we can use parallel multiple declaration.

From

    var height float64
    var weight float64


To

    var heightweight float64


If they are not the same type, we can use the format below.

From

    var number int
    var height float64
    var disabled bool


To

    var (
        number   int
        height   float64
        disabled bool
    )

 

Type Inference



If you know the value ahead of time, you can assign it when declaring.


    var disabled bool = true


The editor may send you a warning message.

Warning: 

   should omit type bool from declaration of var disabled; it will be inferend from the right-hand side.


The reason is that Go can automatically determine the type.

It is called type inference.

1. 'Go' will automatically determine the value's type.
2. The variables should then be declared using that type.

As a result, we can simplify our code as follows.


    var disabled = true



Short declaration



Go provides another variable declaration format that is shorter. (colon followed by an equal sign)


    disabled := true



It is vital to note that using short declarations in package scope will result in an error message.

exp/main.go

package main

import "fmt"

// It is working
var valid = false

// It is not working - short declaration in package scope
disabled := true

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


Error:

    syntax error: non-declaration statement outside function body

 
The reason for this is that all statements in package scope must begin with a keyword such as package, var, or func. Refer to this article.

This rule will make it easier for the Go compiler to parse programs.

Because a short declaration violates this restriction under package scope, Go does not permit it and will throw this error.

It is also worth noting that variables under package scope will live forevers until the program terminates.



Re-declaration



The same variable cannot be declared twice.


    var disabled = true
    var disabled = false


Error:
disabled redeclared in this block
    previous declaration at xxx


 
However, there is an exemption for short declarations.
It works as seen below.


    var t1 = true
    t1t2 := falsetrue
    fmt.Println(t1, t2)


Even though t1 was previously declared, if there are new variables on the left side of:, the short declaration can still be used.
As a result, Go will assign a new value to t1, as well as declare and initialize t2.

Actually, we can update it as follows (in an obvious way).


    var t1 = true
    t1 = false
    t2 := true
    fmt.Println(t1, t2)

 

Normal V.S. Short Declaration



There are some tips to help you decide when to use them.

Normal:

1. If you don't know the value.
2. If you want to use it in the package scope.
3. Group variables for readability.

Short: (We mostly prefer using it)

1. If we know the value.
2. To keep the code concise.
3. For redeclaration.


Assignment



The term "assignment" refers to changing the value of a variable.

The assignment operator is '='.

Go is also a strongly-typed language. As a result, you cannot assign a value of one type to a variable of another type.

Consider the following example.


    var name string
    name = 1
    fmt.Println(name)


Error:

   cannot use 1 (type int) as type string in assignment

 

Beginners frequently make the error of assuming that because int and float64 are both numeric, assigning values between them should work.
However, it is not working.


    myHeight := 190
    var height float64
    height = myHeight // Error
    fmt.Println(height)



Multiple Assignment



We can do the multiple assignment as below.


    var t1 bool
    var t2 bool
    t1t2 = truefalse
    fmt.Println(t1, t2)


In Go, you can use multiple assignment to swap the value.


    var t1 = true
    var t2 = false
    t1t2 = falsetrue
    fmt.Println(t1, t2)



Type Conversion



Different types cannot do the calculation together.


    var t1 = 1
    var t2 = 2.5
    fmt.Println(t1 + t2)


Error:

   invalid operation: t1 + t2 (mismatched types int and float64)



The reason is that Go did not support implicit conversion.
It required us to do it by ourselves (less error-prone). Refer to this doc.

As a result, we must perform a type conversion before computing them.
We can alter the type of a value to another type via type conversion. (NOTE: the type of variable, not the type of variables)

* Format:

    type(value)


    var t1 = 1
    var t2 = 2.5
    fmt.Println(float64(t1) + t2)


No comments:

Post a Comment