The keyword

Variable declarations

A standard format

    varVariable name Variable typeCopy the code
    var name string;
    var age int 
    var isFemale bool
Copy the code

Batch statements

    var (
        name string
        age int
        ifFemale bool
    )
Copy the code

Ps: Go language after the global variable declaration, variables must be used

package main
import "fmt"
func main(a) {
    name: 'soana'
    age: 23
    isFemale: false
    
    fmt.Print(age) // Outputs the printed content in the terminal
    fmt.Printl("name:%s", name) //%s: placeholder, using the name variable to replace the placeholder
    fmt.PrintLn(age) // A newline character is added after printing the specified content
}

Copy the code
//1. Declare variables and assign values
var name string = 'jbw'  / / do not recommend

//2. Recommendation is type inference (same mechanism as TS)
var name ='jbw'

//3. Short variable declarations can only be used inside functions

func main (a) {
    str := 'jbw'
}
Copy the code

2 and 3 are type inference. You can determine the type of a variable based on the initial value set by default. In actual scenarios, batch declaration and short variable declaration are recommended.

Matters needing attention:

1. All statements outside the function must start with a keyword (func, package, var/const, import, etc.). 2.:= not available outside the function. 3._ Mostly used as placeholders, indicating that values are ignored. 4. You cannot declare a variable more than once in the same scope