Golang variables
- Three ways to use Golang variables
- Variable declaration, initialization and assignment
- The use of the + sign in the program
- Basic introduction to data types
- decimal type/float type
- character type
- Boolean type
- string type
- Default values for primitive data types
- Mutual conversion of basic data types
- Conversion of data types and strings
- string type to basic data type
- pointer
- Value Types and Reference Types
case:
Three ways to use Golang variables
-
The first method: specify the variable type, if no value is assigned after declaration, the default value will be used
- If the variable of Golang is not assigned an initial value, the compiler will use the default value
- For example, the default value of int is 0, the default value of string is empty string, and the default value of decimal is 0
-
The second type: determine the variable type by itself according to the value (type deduction), do not use the default value
-
The third: omit var
- Note: The variable on the left of = should not have been declared, otherwise it will cause a compilation error
- Note: The variable on the left of = should not have been declared, otherwise it will cause a compilation error
-
The fourth type: multi-variable declaration
- In programming, sometimes we need to declare multiple variables at once, and Golang also provides such syntax
- In programming, sometimes we need to declare multiple variables at once, and Golang also provides such syntax
Variable declaration, initialization and assignment
The use of the + sign in the program
package main
import "fmt"
//演示golang中+的使用
func main() {
var i = 1
var j = 2
var r = i + j //做加法运算
fmt.Println("r=", r)
var str1 = "hello "
var str2 = "world"
var res = str1 + str2 //做拼接操作
fmt.Println("res=", res)
}
- When both the left and right sides are numeric, do the addition operation
- When both the left and right sides are strings, do string splicing
- Not allowed one is a character, the other is another type
- Not allowed one is a character, the other is another type
Basic introduction to data types
integer type
- Simply put, it is used to store integer values, such as 0, -1, 2345 and so on.
The unsigned type of int:
Description of other types of int:
Integer usage details
-
Golang has various integer types: signed and unsigned, and the size of int uint depends on the system.
-
Golang's integer type is declared as int by default
-
How to view the byte size and data type of a variable in the program (used more)
-
When using integer variables in Golang programs, follow the principle of keeping small but not big
- That is: under the condition of ensuring the correct operation of the program, try to use a data type that occupies a small space.
- That is: under the condition of ensuring the correct operation of the program, try to use a data type that occupies a small space.
-
bit: The smallest unit of storage in a computer.
-
byte: The basic storage unit in a computer.
- [Binary in detail] 1byte = 8 bit
decimal type/float type
- The decimal type is used to store decimals, such as 1.2 0.23 -1.911
Classification of decimal types
Explanation of the above picture:
- A brief description of the storage form of floating-point numbers in the machine, floating-point number = sign bit + exponent bit + mantissa bit
- Explanation: Floating point numbers are signed
var price float32 = 89.12
fmt.Println("price=", price)
var num1 float32 = -0.00089
var num2 float64 = -7809656.09
fmt.Println("num1=", num1, "num2=", num2)
- The mantissa part may be lost, resulting in a loss of precision. -123.0000901
//尾数部分可能丢失,造成精度损失。 -123.0000901
var num3 float32 = -123.0000901
var num4 float64 = -123.0000901
fmt.Println("num3=", num3, "num4=", num4)
Explanation: The precision of float64 is more accurate than that of float32.
Explanation: If we want to save a number with high precision, we should choose float64
- The storage of floating-point type is divided into three parts: sign bit + exponent bit + mantissa bit. During the storage process, the precision will be lost.
- Generally, precision is lost when the mantissa is a decimal
Floating-point usage details
- Golang floating-point types have a fixed range and field length, which are not affected by the specific OS (operating system).
- Golang's floating-point type is declared as float64 by default.
- That is, the largest range
//Golang 的浮点型默认声明为float64 类型
var num5 = 1.1
fmt.Printf("num5的数据类型是 %T \n", num5)
- Floating-point constants have two representations
- Decimal number form: such as: 5.12 .512 (must have a decimal point)
- Scientific notation form: such as:
- 5.1234e2 = 5.12 * 10 to the power of 2
- 5.12E-2 = 5.12/10 to the power of 2
//十进制数形式:如:5.12 .512 (必须有小数点)
num6 := 5.12
num7 := .123 //=> 0.123
fmt.Println("num6=", num6, "num7=", num7)
//科学计数法形式
num8 := 5.1234e2 // ? 5.1234 * 10的2次方
num9 := 5.1234E2 // ? 5.1234 * 10的2次方 shift+alt+向下的箭头
num10 := 5.1234E-2 // ? 5.1234 / 10的2次方 0.051234
fmt.Println("num8=", num8, "num9=", num9, "num10=", num10)
- Normally, float64 should be used because it is more precise than float32.
- [Under development, float64 is recommended]
character type
- There is no special character type in Golang. If you want to store a single character (letter), you generally use byte to save it.
- A string is a sequence of characters connected by a string of fixed-length characters.
- Go strings are concatenated from individual bytes.
- That is to say, traditional strings are composed of characters, but Go's strings are different, they are composed of bytes.
- That is, we cannot print strings in the normal way, and the strings printed in the normal way are code values
- That is, we cannot print strings in the normal way, and the strings printed in the normal way are code values
var c1 int = '北'
fmt.Println("c1=", c1, unsafe.Sizeof(c1))
var c1 = '北'
fmt.Printf("c1=%c", c1)
Explanation of the above code
- If the characters we save are in the ASCII table, such as [0-1, az, AZ...] can be directly saved to byte
- If the corresponding code value of the character we save is greater than 255, then we can consider using the int type to save
- If we need to output according to the character, then we need to format the output
- That is, fmt.Printf("%c", c1)
Character Type Usage Details
- A character constant is a single character enclosed in single quotes ('').
- For example: var c1 byte = 'a'
- var c2 int = '中' var c3 byte = '9' 2)
- Go allows the escape character '\' to convert the following characters into special character constants.
- For example: var c3 char = '\n' // '\n' means newline
- Characters in Go language use UTF-8 encoding, if you want to query the utf8 code value corresponding to the character
- http://www.mytju.com/classcode/tools/encode_utf8.asp
- English letters - 1 byte Chinese characters - 3 bytes
- In Go, the essence of a character is an integer, and when it is directly output, it is the code value of the UTF-8 encoding corresponding to the character.
- You can directly assign a number to a variable, and then press %c to format the output, and the unicode character corresponding to the number will be output
var c1 = 22269
fmt.Printf("c1=%c", c1)
- The character type can be operated, which is equivalent to an integer, because it corresponds to a Unicode code
- Note the single quotes
- Note the single quotes
Discussion on the nature of character types
- The character type is stored in the computer, and the code value (integer) corresponding to the character needs to be found out
- Storage: character—>corresponding code value——>binary—>storage
- Read: binary ----> code value ----> character --> read
- The correspondence between characters and code values is determined by the character encoding table (it is specified)
- The encoding of the Go language is unified into utf-8. It is very convenient and unified, and there is no trouble of garbled coding anymore
Boolean type
- The Boolean type is also called the bool type, and the bool type data only allows the values true and false
- The bool type occupies 1 byte.
- The bool type is suitable for logic operations and is generally used for program flow control
//演示golang中bool类型使用
func main() {
var b = false
fmt.Println("b=", b)
//注意事项
//1. bool类型占用存储空间是1个字节
fmt.Println("b 的占用空间 =", unsafe.Sizeof(b) )
//2. bool类型只能取true或者false
}
string type
- A string is a sequence of characters connected by a string of fixed-length characters.
- Go strings are concatenated from individual bytes.
- The bytes of strings in the Go language use UTF-8 encoding to identify Unicode text
//string的基本使用
var address string = "北京长城 110 hello world!"
fmt.Println(address)
string usage notes and details
- The bytes of strings in the Go language use UTF-8 encoding to identify Unicode text
- In this way, Golang uniformly uses UTF-8 encoding, and the problem of Chinese garbled characters will no longer bother programmers.
- Once a string is assigned a value, the string cannot be modified: strings are immutable in Go.
// Once the string is assigned, the string cannot be modified: in Go, the string is immutable
var str = “hello”
str[0] = 'a' //The content of str cannot be modified here, ie Strings in Go are immutable.
Two representations of strings
- double quotes, escape characters are recognized
//输出源代码等效果 【案例演示】
str2 := "abc\nabc"
fmt.Println(str2)
- Backticks, output in the native form of the string, including newlines and special characters, can achieve effects such as preventing attacks and outputting source code
//使用的反引号 ``
str3 := `
package main
import (
"fmt"
"unsafe"
)
//演示golang中bool类型使用
func main() {
var b = false
fmt.Println("b=", b)
//注意事项
//1. bool类型占用存储空间是1个字节
fmt.Println("b 的占用空间 =", unsafe.Sizeof(b) )
//2. bool类型只能取true或者false
}
`
fmt.Println(str3)
- String concatenation
//字符串拼接方式
var str = "hello " + "world"
str += " haha!"
fmt.Println(str)
- When a line of string is too long, you need to use a multi-line string, which can be handled as follows
//当一个拼接的操作很长时,可以分行写,但是注意,需要将+保留在上一行
str4 := "hello " + "world" + "hello " + "world" + "hello " +
"world" + "hello " + "world" + "hello " + "world" +
"hello " + "world"
fmt.Println(str4)
Default values for primitive data types
In go, data types have a default value. When the programmer does not assign a value, the default value will be retained. In go, the default value is also called zero value.
var a int // 0
var b float32 // 0
var c float64 // 0
var isMarried bool // false
var name string // ""
//这里的%v 表示按照变量的值输出
fmt.Printf("a=%d,b=%v,c=%v,isMarried=%v name=%v", a, b, c, isMarried, name)
Mutual conversion of basic data types
Unlike java/c, Golang requires explicit conversions when assigning values between variables of different types. That is to say, data types in Golang cannot be automatically converted.
basic grammar
- The expression T(v) converts the value v to type T
- T: is the data type, such as int32, int64, float32, etc.
- v: is the variable that needs to be converted
var i int32 = 100
//希望将 i => float
var n1 float32 = float32(i)
var n2 int8 = int8(i)
var n3 int64 = int64(i) //低精度->高精度
fmt.Printf("i=%v n1=%v n2=%v n3=%v \n", i ,n1, n2, n3)
Precautions for mutual conversion of basic data types
- In Go, the conversion of data types can be from a small range –> a large range, or a large range –> a small range
- What is converted is the data stored in the variable (that is, the value), and the data type of the variable itself has not changed!
var i int32 = 100
//被转换的是变量存储的数据(即值),变量本身的数据类型并没有变化
fmt.Printf("i type is %T\n", i) // int32
- In conversion, such as converting int64 to int8 [-128—127], no error will be reported when compiling, but the conversion result is treated as overflow, which is different from the result we hoped for.
- So when converting, you need to consider the range
//在转换中,比如将 int64 转成 int8 【-128---127】 ,编译时不会报错,
//只是转换的结果是按溢出处理,和我们希望的结果不一样
var num1 int64 = 999999
var num2 int8 = int8(num1)
fmt.Println("num2=", num2)
Conversion of data types and strings
- Method 1: fmt.Sprintf("% parameter", expression)
var num1 int = 99
var num2 float64 = 23.456
var b bool = true
var myChar byte = 'h'
var str string //空的str
//使用第一种方式来转换 fmt.Sprintf方法
str = fmt.Sprintf("%d", num1)
fmt.Printf("str type %T str=%q\n", str, str)
str = fmt.Sprintf("%f", num2)
fmt.Printf("str type %T str=%q\n", str, str)
str = fmt.Sprintf("%t", b)
fmt.Printf("str type %T str=%q\n", str, str)
str = fmt.Sprintf("%c", myChar)
fmt.Printf("str type %T str=%q\n", str, str)
- Method 2: Use the functions of the strconv package
var num3 int = 99
var num4 float64 = 23.456
var b2 bool = true
str = strconv.FormatInt(int64(num3), 10)
fmt.Printf("str type %T str=%q\n", str, str)
// strconv.FormatFloat(num4, 'f', 10, 64)
// 说明: 'f' 格式 10:表示小数位保留10位 64 :表示这个小数是float64
str = strconv.FormatFloat(num4, 'f', 10, 64)
fmt.Printf("str type %T str=%q\n", str, str)
str = strconv.FormatBool(b2)
fmt.Printf("str type %T str=%q\n", str, str)
//strconv包中有一个函数Itoa
var num5 int64 = 4567
str = strconv.Itoa(int(num5))
fmt.Printf("str type %T str=%q\n", str, str)
string type to basic data type
- When using the functions of the strconv package
var str string = "true"
var b bool
b, _ = strconv.ParseBool(str)
fmt.Printf("b type %T b=%v\n", b, b)
var str2 string = "1234590"
var n1 int64
var n2 int
n1, _ = strconv.ParseInt(str2, 10, 64)
n2 = int(n1)
fmt.Printf("n1 type %T n1=%v\n", n1, n1)
fmt.Printf("n2 type %T n2=%v\n", n2, n2)
var str3 string = "123.456"
var f1 float64
f1, _ = strconv.ParseFloat(str3, 64)
fmt.Printf("f1 type %T f1=%v\n", f1, f1)
Precautions for converting string to basic data type
- When converting the String type into a basic data type, make sure that the String type can be converted into valid data
- For example, we can convert "123" into an integer, but we cannot convert "hello" into an integer.
- If you do, Golang directly converts it to 0
- The same is true for other types. float => 0 bool => false
//注意:
var str4 string = "hello"
var n3 int64 = 11
n3, _ = strconv.ParseInt(str4, 10, 64)
fmt.Printf("n3 type %T n3=%v\n", n3, n3)
pointer
-
The basic data type, the variable stores the value, also called the value type
-
To get the address of a variable, use &
- For example: var num int, get the address of num: &num
- For example: var num int, get the address of num: &num
-
Pointer type, the pointer variable stores an address, and the space pointed to by this address stores the value
- For example: var ptr *int = &num
- For example: var ptr *int = &num
//基本数据类型在内存布局
var i int = 20
// i 的地址是什么,&i
fmt.Println("i的地址=", &i)
//下面的 var ptr *int = &i
//1. ptr 是一个指针变量
//2. ptr 的类型 *int
//3. ptr 本身的值&i
var ptr *int = &i
fmt.Printf("ptr=%v\n", ptr)
fmt.Printf("ptr 的地址=%v", &ptr)
fmt.Printf("ptr 指向的值=%v", *ptr)
-
Get the value pointed to by the pointer type, use: *, for example: var ptr int, use ptr to get the value pointed to by ptr
- fmt.Printf("value pointed to by ptr=%v", *ptr)
- fmt.Printf("value pointed to by ptr=%v", *ptr)
-
Write a program to get the address of an int variable num and display it to the terminal
-
Assign the address of num to the pointer ptr, and modify the value of num through ptr
Pointer usage details
- Value types have corresponding pointer types, in the form of *data type
- For example, the pointer corresponding to int is *int, and the pointer type corresponding to float32 is *float32
- Value types include: basic data types int series, float series, bool, string, array and structure struct
Value Types and Reference Types
-
Value type: basic data type int series, float series, bool, string, array and structure struct
-
Reference types: pointers, slices, maps, pipeline channels, interfaces, etc. are all reference types. The
usage characteristics of value types and reference types -
Value type: Variables store values directly, and memory is usually allocated on the stack
-
Reference type: The variable stores an address, and the space corresponding to this address actually stores data (value)
-
Memory is usually allocated on the heap. When no variable refers to this address, the data space corresponding to this address becomes a garbage, which is reclaimed by GC
-
Schematic diagram of the stack area and heap area of memory