Go for beginners | Variables



Let's get started and we are going to talk about variables in golang. There are many ways to declare a variable. 

1. Declare then assign (two steps):
var firstNumber int
firstNumber = 1
This is one way to create a variable. First, it has the keyword var (variable). Then, I name the variable as firstNumber. firstNumber is going to hold whole numbers for integers (the type int).
Next step, I will assign a value of 1 to firstNumber.

2. Declare and assign a value at the same time (with no type):
var secondNumber =2
That's another way of declaring a variable. First, I still use the keyword var. Next, I will call the variable as secondNumber. Different from the first example, rather than leave the type of variable int. I am going to follow the variable with an equal sign. Finally, this one is equal to 2.

3. Short variable:
thirdNumber := 3
sum := firstNumber + secondNumber

Short variable declaration is a very convenient manner in Go. The Go compiler will infer the type according to the value.

Pitfalls must pay attention to when using short variables:
- Short variables can only be used in functions

package main
i := 10
func main() {
    fmt.Println(i)
}

The compiler will complain: syntax error: non-declaration statement outside function body

- Declare at least one new variable like the source code bellow

package main

import "fmt"

func main() {
    var i = 1

    i, err := 2, true

    fmt.Println(i, err)
}

In this example, the statement "i, err := 2 , true" declares only one new variable err, the i variable is actually declared in "var i =1".

- Short variable shadow under the global variable declaration.

package main

import "fmt"

var i = 1

func main() {

    i, err := 2, true

    fmt.Println(i, err)
}

In this example, "“i, err := 2, true” will declare new variable i, which makes the global i inaccessible in the main function. To use the global variable, the solution is:
“package main

import "fmt"

var i int

func main() {

    var err bool

    i, err = 2, true

    fmt.Println(i, err)
}”

5. There are some other rules you have to remember when naming variables in go.
- Can't begin with the number.
var 1stNumber int
The compiler will complain: expected 'IDENT', found 1 syntax

- Go allowed us to naming variables that begin with the underscore.

var _firstNumber int

- The variable's name begins with the letter which can be an upper case or lower case letter are different.


- Once you declare a variable, you have to use it. 
The compiler will complain: firstNumber declared but not used



Reference:
Golang-101-hacks by 
go crash course with Trevor Sawler

Post a Comment

Comment

Previous Post Next Post
WANG !!!!!
https://s.shopee.vn/609U3II1Xf