Basics
1. Variable usage details
(1) Declare variables
Naming principles
Go language variable names consist of letters, numbers, and underscores, where the first letter cannot be a number.
Declaration and initialization methods
The general form of declaring and initializing variables is to use the var keyword and ':'
1. Declaring variables (the most concise)
judges the variable type according to the value, and omitting 'var' with ':'
package main
import "fmt"
func main() {
a, b, c := 1, 2, 3
fmt.Println("你的值是:", a, b, c)
}
2. Declare variable var (no value is assigned after declaration, int is the default value 0, string is the default value empty string)
package main
import "fmt"
func main() {
var a, b, c int
fmt.Println("你的值是:", a, b, c)
}
3. Global variable declaration
```go
package main
import "fmt"
var (
a, b, c = 1, 2, 3
)
func main() {
fmt.Println("你的值是:", a, b, c)
}
(2) View and conversion of variable types and sizes
1. Type size, type view
package main
import (
"fmt"
"unsafe"
)
var a, b, c, d int
func main() {
a = 1
fmt.Printf("a的数据类型是:%T,字节大小是:%d ", a, unsafe.Sizeof(a))
}
2. Type conversion The
basic format of Go language type conversion is as follows:
type_name(expression)
Where type_name is the data type and expression is the original data or expression.
package main
import(
"fmt"
)
func main() {
var a uint = 8
var b byte = 8
//c := byte(a)
fmt.Println(byte(a)==b)
//将a转换为byte型,并与b相比查看是否等价
note:
For example (int8 range is -128 ~ 127)
3. Floating point type
In Go, float64 is quite double
float64 and is more accurate than float32
4. Character
There is no special character type in Go. If you want to store a single character (letter), generally use byte.
A character string is a sequence of characters connected by a series of fixed-length characters.
The Go string is different, it consists of bytes.
Character type essence discussion
5. String type
Introduction: A character string is a sequence of characters connected by a string of fixed-length characters.
The Go string is different, it consists of bytes.
Notes on use:
1) Once a string is assigned in Go, it cannot be modified
2) Two representations:
(1) Double quotes, will recognize the escape character
(2) Backquotes, output as the string, including newlines And special characters, can prevent attacks, output source code, etc. (ie, escape characters are not recognized)
package main
import "fmt"
func main() {
a := "识别转义字符!\n"
b := `不识别"转义"字符!`
fmt.Println(a, b)
}
3) String concatenation
, that is, when concatenating multiple lines of strings, + must be at the end of the line before it will be cut;