【Go】Basic syntax--defining variables

Start learning the first go statement

Defining variables

First look at the simple go program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import (
     "fmt"
)

func main() {
    // Define a variable name of type string and initialize it to "Bill Gates"
    var name string = "Bill Gates"

    // Define a variable int of type int and initialize it to 32
    var age int = 29

    // Define a variable height of type int, not initialized, but go will default to 0
    var height int

    // Define a variable of type bool isRight, not initialized, but go will default to false
    var isRight bool

    fmt.Println(name)
    fmt.Println(age)
    fmt.Println(height)
    fmt.Println(isRight)
}

Save as helloworld.go and run to see the output

1
2
3
4
5
[me@VM_0_14_centos go] # go run helloworld.go
Bill Gates
29
0
false

Short variable declaration

: =

1
2
// equivalent to var sum int = 1
sum: = 1

go will automatically infer the type of the variable based on the type

Generally recommended in functions or loop structures

Persist in original technology sharing, your support will encourage me to continue to create!