go constants, variables

Skip the installation process and
write the first go program, output "hello wolrd"

package main

import (
    "fmt"
)

func main() {
    
    
    fmt.Print("hello wolrd")
}

All .go files have a package keyword, which is used to declare which package the
file is in. The main function in main will become an executable file after compilation. The
import keyword is used as the entry point of the program to import the package.

Declare variables
. The definition of variable names in the Go language is recommended to use small camel case naming

Standard declaration variable format
var variable name variable type

Declare variables in bulk

var (
    a string
    b int
    c bool
    d float32
)

Non-global variables in the Go language must be used after declaration. If they are not used, the compilation will not pass. After global variables are declared, they can not be used.

Simultaneous assignment of variable declarations

var s1 string = "dong"
var s1  = "dong"

Short variable naming (can only be used in functions)

ss := 123

Anonymous variables
When using multiple assignments, if you want to ignore a certain value, you can use anonymous variables. Anonymous variables are represented by _.
Anonymous variables do not occupy namespace and do not allocate memory, so there is no duplicate declaration

a, _ := 1, 2

Constant
keyword const

const a = 100

Batch constant declaration

const (
    a = 1
    b = 2
    c = 3
    d = 4
)

common problem

const (
    a = 1 //1
    b     //1
    c     //1
    d     //1
)

In this code, the values ​​of b, c, and d are all zero.
When defining constants in batches, if no value is assigned to the constant, then its value is the same as the value in the previous line. The
Iota
Iota keyword is reset to zero after the const appears. For each new line in const, iota will count once and +1 each time (iota can be understood as the index of the const statement block). Using iota can simplify the definition, which is very useful when defining enumerations. For
example

const (
    a = iota //0
    b     //1
    c     //2
    d     //3
)

The use of iota in const will not be affected by _

const (
    a = iota //0
    b     //1
    _     //2
    d     //3
)

Will not be affected by assignment

const (
    a = iota //0
    b = 100  //100
    c = iota //2
    d        //3
)

The value of iota in each row is the same

const (
    a1,a2 = iota+1,iota+2 //a1 = 1,a2 = 2
    b1,b2 = iota+1,iota+2 //b1 = 2,b2 = 3
)

Define the order of magnitude (<< sign is a binary left shift sign)

const (
    KB = 1 << (10 * iota)
    MB = 1 << (10 * iota)
    GB = 1 << (10 * iota)
    TB = 1 << (10 * iota)
    PB = 1 << (10 * iota)
)

Guess you like

Origin blog.csdn.net/weixin_44865158/article/details/114187039