02 Golang variables and data types

Definition and use of variables

Variable definition syntax: var 变量名 数据类型
local variables: variables defined in the statement block (such as methods)
global variables: variables defined outside the statement block

Variable declaration method:

  1. Specify the variable type, and use the default value if no value is assigned after declaration
  2. Judge the variable type based on the value
  3. Omit var and use:= assignment, the variable on the left cannot be already declared, otherwise an error will be reported
  4. Support multi-variable declaration (both local variables and global variables are supported), see sample code

Sample code

//全局变量声明
var gn1 = 100
var gn2 = "jack"
//一次声明多个全局变量
var (
	gn3 = 200
	gn4 = "mary"
)

func test(){
    
    
	//变量使用方式1:指定变量类型,声明后如果不赋值则使用默认值
	var i  int
	fmt.Println("i1=",i)

	//变量使用方式2:根据值自行判断变量类型
	var i2 = 2
	fmt.Println("i2=",i2)

	//变量使用方式3:省略var 使用 := 赋值,左侧变量不能是已经声明过的,否则报错
	i3 := "4"
	fmt.Println("i3=",i3)


	//一次声明多个变量 方式1
	var n1, n2, n3 int
	fmt.Println("n1=",n1,"n2=",n2,"n3=",n3)

	//一次声明多个变量 方式2
	var n12, n22, n32 = 100, "tom", 200 
	fmt.Println("n1=",n12,"n2=",n22,"n3=",n32)

	
	//一次声明多个变量 方式3
	n13, n23, n33 := 200, "tom", 300 
	fmt.Println("n1=",n13,"n2=",n23,"n3=",n33)

    //输出全局变量
	fmt.Println("全局变量:gn1=",gn1,"gn2=",gn2,"gn3=",gn3,"gn4",gn4)

	n13 = 133  
	//n13 = n23; 该行报错,不能改变变量的类型

}

Basic data type

Basic data types, including
1) Numerical type: integer: int, int8, int16, int32, int64 Floating-point type: float32, float64
2) Character type: there is no special character type, use byte to store a single alphabetic character
3) Boolean type : true false
4) String: String is officially defined as a basic type
derived/complex data type, including:
1) pointer
2) array
3) structure struct
4) channel
5) function
6) slice
7) Interface
8) map

Integer

Variables that store integers, including signed integers, unsigned integers, and other types of integers. The default value is 0.
Signed integers:
Insert picture description here
unsigned integers:
Insert picture description here
other types of integers:
Insert picture description here
sample code:

func test2(){
    
    
	var i int
	fmt.Println("i=",i);
	
	//有符号整型测试
	//var i2 int8 = 128 // 报错超过 constant 128 overflows int8
	var i2 int8 = 127  //正常
	fmt.Println("i2=",i2);

    //无符号整型测试
	//var i3 uint8 = 256 // 报错超过 constant 256 overflows uint8
	//var i3 uint8 = -1  //报错 constant -1 overflows uint8
	var i3 uint8 = 255 //正常
	fmt.Println("i23=",i3);

	//其他类型整型
	var a int = 999
	fmt.Println("a=",a);

	var b unit = 1
	var c byte = 255
	fmt.Println("a=",a,"b=",b,"c=",c);


}

important point

  1. The size of int and uint is related to the system, and the range of other types has nothing to do with the system
  2. Integer declaration default type is integer
  3. Check the variable size and the number of bytes occupied by
    fmt.Printf("The number of bytes occupied by the type %T of i3 is %d", i3, unsafe.Sizeof(i3))
  4. When using integer variables in a Golang program, try to use data types that occupy a small space under the premise of satisfying the normal operation of the program.

Floating point

The data type used to store the decimals
. The storage format of the floating-point type in the machine: floating-point number = sign bit + exponent bit + mantissa bit
Default value 0
classification
Insert picture description here

Sample code

func test3(){
    
    
	var price float32 =12.13
	fmt.Println("price=",price);
	var price2 float32 =-0.000098
	var price3 float64 =-8999.09
	fmt.Println("price2=",price2,"price3=",price3)

	//精度丢失测试
	var price4 float32 =12.130000901
	var price5 float64 =12.130000901
	//输出 price4= 12.130001 price5 12.130000901   float32 发生精度丢失
	//float64 精度比 float32 精度高
	fmt.Println("price4=",price4,"price5",price5)
	var num float64 = 5.12334423e2
	var num2 float64 = 5.123344233E-2
	
}

important point

  1. Floating point numbers are signed
  2. The number of bits may be lost, resulting in loss of precision. The precision of float64 is not higher than float32
  3. The floating-point type is declared as float64 by default
  4. Two commonly used representations of floating point:
    Decimal: 5.12 .512 must have a decimal point.
    Scientific notation: 5.123e2 = 5.12*10 to the second power 5.123E-2 = 5.12/10 to the second power E can be uppercase or lowercase

Character type

There is no special character type in Golang. If you want to store a character, you generally use byte to save it. A string is a sequence of characters connected by a fixed-length character. Go's string roommates are concatenated with a single byte.
Sample code

func test01(){
    
    
	var c1 byte = 'a'
	var c2 byte = '0'
	fmt.Println("c1=",c1);
	fmt.Println("c2=",c2);
	//c1= 97 c2= 48  tyte输出时默认输出码值  如果希望输出字符串 需要格式化输出
	fmt.Printf("c2= %c c1= %c",c2,c1) //c2= 0 c1= a
	//var c3 byte = '北' // 报错 constant 21271 overflows byte
	var c3 = '北' // 字符被默认成int32 类型
	fmt.Println("c3 =",c3);
	fmt.Printf("c3的类型 %T 占用的字节数是 %d", c3, unsafe.Sizeof(c3))
		//输出:c3的类型 int32 占用的字节数是 4
	var num = 10 + 'a'
	fmt.Println("num = ", num )//输出 107

}

important point

  1. If the character we save is in the ascii table, it can be saved directly to byte, and if the corresponding code of the character is greater than 255, it can be saved in the int type.
  2. The characters in the go language use UTF-8 encoding (English 1 byte Chinese characters 3 bytes), if you want to query the utf-8 code value corresponding to the character, visit: http://www.mytju.com/classcode/tools/encode_utf8. asp
  3. A character in go is essentially an integer, and when it is output directly, it outputs the value of the UTF-8 code corresponding to the character. The output characters need to be formatted and output fmt.Printf("c2= %c c1= %c",c2,c1)
  4. You can directly assign integers to variables and format the corresponding characters
  5. The character type is equivalent to an integer that can be operated on.
  6. To store the character type in the computer, it is necessary to convert the code value corresponding to the character into a binary system for storage.
    Storage: Character -> Code Value -> Binary -> Storage Read: Just the opposite of storage
  7. The relationship between characters and code values ​​is determined by the character code table (pre-appointed)
  8. Go language coding uniformly uses utf-8, which is very convenient and has no trouble with garbled codes.

Boolean type

The bool type only allows two values, true and false, which occupies one byte, the
default value: false
Sample code

 func test02(){
    
    
	var b = false
	fmt.Println(b)
	//b的类型 bool 占用的字节数是 1
	fmt.Printf("b的类型 %T 占用的字节数是 %d",b , unsafe.Sizeof(b))
}
   

string type

A string is a sequence of characters concatenated with fixed-length characters. Go's strings are connected by single bytes. Byte uses UTF-8 encoding to identify Unicode text.
Default value: ""
Sample code

func test03(){
    
    
	var str string = "北京欢迎你1"
	//str ="haha "
	fmt.Println(str[0])//229
	//str[0] = 1  报错 字符串内容无法修改
	//str的类型 string 占用的字节数是 16
	fmt.Printf("str的类型 %T 占用的字节数是 %d",str , unsafe.Sizeof(str))
	var str2 string =`adasdfa\n \t`
	var str3 string ="adasdfa\n \t"
	
	fmt.Println(str2)//输出 16adasdfa\n \t  不会通过 \转义字符
	fmt.Println(str3)//输出 16adasdfa

	str = str + "123"
	fmt.Println(str)

	str += "haha"
	fmt.Println(str)
	//当一个字符串很长时,可以通过加号分行写 但是加号要写在上一行
	var str5 = "haha" +
	"hah123" + " test "+
	"asdfas"
	fmt.Println(str5)
}

important point

  1. The content of the string cannot be modified after the value is assigned (the content of one of the bytes)
  2. Two string definition methods "123\n" 123\n(characters will not be escaped)

Basic data type conversion

Golang does not support automatic conversion of variable types, and the
basic syntax must be explicitly converted : the expression T(v) converts the value v to the type T

Sample code

func test04(){
    
    
	var i int32 = 100
	var f float32 = float32(i)
	fmt.Println(f)//100
	//i的类型 int32 占用的字节数是 4
	fmt.Printf("i的类型 %T 占用的字节数是 %d",i , unsafe.Sizeof(i))

	var n1 int32 = 10
	var n2 int64

	//n2 = n1 +10 会报错 因为类型不符
	n2 = int64(n1)+10
	fmt.Println("n2 = ",n2)//20
	var n4 = 200
	var n3 int8 =10
	n3 = int8(n4)+10
	fmt.Println("n3 = ",n3)//-46 由于类型范围问题 导致计算结果不准

	//--------------基本类型 转string
	var i1 int =99
	var f1 float32 =32.23
	var b bool = true
	var c1 byte = 'a'
	var str string
	str = fmt.Sprintf("%d",i1)
	fmt.Println("str = ",str)
	fmt.Printf("str的类型 %T 占用的字节数是 %d \n",str , unsafe.Sizeof(str))
	str = fmt.Sprintf("%f",f1)
	fmt.Println("str = ",str)
	fmt.Printf("str的类型 %T 占用的字节数是 %d \n",str , unsafe.Sizeof(str))
	str = fmt.Sprintf("%t",b)
	fmt.Println("str = ",str)
	fmt.Printf("str的类型 %T 占用的字节数是 %d \n",str , unsafe.Sizeof(str))
	str = fmt.Sprintf("%c",c1)
	fmt.Println("str = ",str)
	fmt.Printf("str的类型 %T 占用的字节数是 %d \n",str , unsafe.Sizeof(str))

	str = strconv.FormatInt(int64(i1),10)
	str = strconv.FormatBool(b)
	str = strconv.FormatFloat(float64(f1),'f',10,64)
	
	//-----------string转基本类型
	var ss string = "123"
	var ss2 string = "true"
	var ss3 string ="123.123"
	var in1,_ = strconv.ParseInt(ss,10,64)
	fmt.Println(in1)
	var bo,_ = strconv.ParseBool(ss2)
	fmt.Println(bo)
	var fl,_ = strconv.ParseFloat(ss3,64)
	fmt.Println(fl)
}

important point

  1. Two ways
    to convert common types to strings: call fmt.Sprintf("%t",b)
    call strconv.FormatBool(b)
  2. To convert a string to a common type, directly use the strconv package method, such as: strconv.ParseInt(ss,10,64)
  3. When converting a string to a basic type, make sure that the string format is correct. If you can’t convert hello to int type, other types are also similar to float to 0 and boolean to false.

Pointer type

The basic data type variable stores a value, also called a value type. The pointer variable stores an address, and the space pointed to by this address stores the value.

var ptr *int = &num  //表示用ptr 变量保存 num变量的值的地址

Sample code

func test4(){
    
    
	var i int = 10
	fmt.Println("i的地址=",&i)

	var ptr = &i
	fmt.Println("i的地址=",ptr)

	fmt.Println("ptr的地址=",&ptr)

	fmt.Println("ptr指针地址保存的值=",*ptr)

	//ptr的类型 *int 占用的字节数是 8 
	fmt.Printf("ptr的类型 %T 占用的字节数是 %d", ptr, unsafe.Sizeof(ptr))
}

important point

  1. Get the variable address with the ampersand, such as: &num is the address where the value of the num variable is saved
  2. The pointer type represents a memory address. Variables of all value types (including: integer, floating point, bool, string array, structure) have corresponding pointer types, in the form of: *variable type, such as: * int * int8 * int32 * int64 * float32
  3. Get the value of the address saved by the pointer variable using *, such as: *ptr Get the pointer ptr points to the value saved in the address

Value type and reference type

Value type: Including: integer, floating point, bool, string array, structure variable address directly save the value, memory is usually allocated in the stack, the memory diagram is as follows:
Insert picture description here

Reference type: The variable stores an address, and the space corresponding to this address stores the real value. When there is no variable referencing this address, the value will be recovered as a matter of time. Space is usually allocated in the heap area. The memory diagram is as follows:
Insert picture description here

Identifier and naming convention

Identifier

The string used by Golang for the naming of various variables, methods, functions, etc. becomes the identifier
naming rule

  1. Consists of uppercase and lowercase letters, 0-9 and _
  2. Numbers cannot start
  3. Strictly case sensitive
  4. Cannot contain spaces
  5. A single underscore "_" is a special identifier in Go, called an empty identifier, which can represent any identifier and is only used as a placeholder. Variables or methods cannot be called through this identifier (it represents The value will never be called) For example: the method returns multiple values, and some values ​​can be used to occupy the place when they are not needed. Only as a placeholder, not as an identifier

Naming conventions

  1. Keep the package name consistent with the directory, try to use short and meaningful package names, and do not conflict with standard packages
  2. Variable functions, etc. use camel case nomenclature
  3. In Go, if the first letter of the variable, function, and constant name is capitalized, it means that it can be accessed by other packages (equivalent to public in java). Otherwise it can only be used in this package (equivalent to protected private, etc.)
  4. Do not use reserved keywords and predefined identifiers

Reserved keywords

Insert picture description here
Predefined identifier
Insert picture description here

Guess you like

Origin blog.csdn.net/zhangxm_qz/article/details/114373898