go language learning [2]

Go language basic data types

I Variables and their related contents
II Integer type
III Floating point type
IV Character type
V Boolean type
Vi String type
VII Mutual conversion of basic data types
VIII Pointer

I Variables and their related contents

1. Use steps of variables:

(1) Declare variables (define variables)
(2) Assignment
(3) Use

  • Simple case
package main
import "fmt"
func main() {
	var i int //Define variables
	i=10      //assignment
	fmt.Println("i=",i) //Use variables
}

The output is:

i=10
2. Three ways to use variables

(1) Specify variable type [use default value if no assignment is made after declaration]

var a int
fmt.Println("a=",a)//The output is a=0

(2) Determine the variable type according to the value (type derivation)

var b = 9.99 //The type of b is not specified. The type of b is determined according to the value after the equal sign

(3) Omit var [Note: the variable on the left of = should be undeclared, otherwise it will lead to compilation error]

name := "tom"//If var is omitted, add the following before the equal sign:
/*Equivalent to var name string  
         name = "tom"*/

Note: declare multiple variables at one time:

var a1,a2,a3 int //Define multiple variables of the same type
var num,name,age = 1,"tom",18  // First define different types of variables, and then assign values. The data on the right side of the equal sign is assigned to the left type in turn
num,name,age := 1,"tom",18 //If var is omitted, i.e. no variable is defined, it needs to be used in assignment:=

The output results of the above one-time declaration of variables of different types:

3. Data type of variable

II Integer type

  • View the data type of a variable and the number of bytes occupied
package main
import(
	"fmt"
	"unsafe" //Introducing unsafe package
)

func main() {
	var i = 100
fmt.Printf("i The data type is:%T  i Number of bytes occupied:%d",i,unsafe.Sizeof(i)) //Use the functions in the unsafe package to output the number of variable bytes, FMT Printf() is used to format the output
}

III Floating point type

1) Floating point number = sign bit + exponent bit + trailing digit
2) When using floating-point numbers, the mantissa may be lost, resulting in loss of precision.
3) Floating point type is declared as float64 by default

var num =9.9
fmt.Printf("num Type:%T",num)

The output is:

num Type: float64

4) In general, float64 is used for higher accuracy.

IV Character type

  • There is no special character type in Golang. If you want to store a single character (letter), you usually use byte to save it.
  • Golang strings are composed of bytes, while traditional strings are composed of characters.

About the use of go language character types:

package main
import "fmt"
	
func main() {
	var a byte = 'm'
	var b byte = '0'
	//When the byte value is directly output, the code value corresponding to the character is output
    fmt.Println("a=",a,"\tb=",b) //Here, the output is a = 109 and B = 48
    
    //To output the corresponding characters, you need to use formatted output
    fmt.Printf("a=%c\tb=%c",a,b) //At this time, the output result is characters
}


1) If the characters to be saved are in the ASCII table, they can be directly saved to byte.
2) If the corresponding code value of the character to be saved is greater than 255, it can be saved with int type.
3) If we need to output in character mode, we need to format the output, that is, FMT Printf("%c",c1)…

V Boolean type (bool)

  1. bool type data can only take values of true and false (false and true cannot be replaced by 0 or non-0 integers, which is different from c language)
  2. bool type takes up 1 byte
  3. bool type is suitable for logic operation and is generally used for program flow control.
  4. The default value of bool type is false

Vi String type (bool)

A string is a sequence of characters connected by a string of fixed length characters.

1) The string of Go is connected by a single byte. The bytes of the string of Go language use UTF-8 encoding to identify Unicode text, without the trouble of garbled code.

2) Once the string is assigned, it cannot be modified. In Go, the string is immutable.

3) There are two representations of strings:

  1. Double quotation marks that recognize escape characters
  2. Backquotes are output in the native form of strings, including line breaks and special characters, which can prevent attacks and output source code.
package main
import "fmt"
	
func main() {
	str1 := "abc\nabc" //Escape characters in double quotation marks can be output
	str2 := `package main
	import "fmt"`      //For special characters, only using backquotes can output correctly
	fmt.Println(str1)
	fmt.Println(str2)
}


4) String splicing

//When a splicing operation is very long, it can be written in separate lines. Note: you need to keep + in the previous line
str :="hell0"+"world"+"hell0"+"world"+"hell0"+"world"+
"hell0"+"world"+"hell0"+"world"
fmt.Println(str)

VII Mutual conversion of basic data types

  • Unlike java/c, Golang needs to display conversion when assigning values between variables of different types, that is, data types in Golang cannot be automatically converted.
package main
import "fmt"
	
func main() {
	//Conversion of basic data types in Golang
	var i int =100
	var n1 float32 = float32(i) //Convert i to float32 type
	fmt.Printf("i=%v n1=%v",i,n1) // %v means output according to the value of the variable
}

The output is:

i=100 n1=100

Note: what is converted is the data stored in the variable (i.e. value), and the data type of the variable itself has not changed! (the data type of I here is still int)

  • Convert basic data type to string
package main
import (
    "fmt"
    "strconv"
	)
func main() {
	//Use FMT Sprintf method conversion (method 1)
	var num1 int = 16
	 var str string //Empty str
	str = fmt.Sprintf("%d",num1)//Convert the value stored in num1 into string type and return the value to str
    fmt.Printf("str Type:%T  str=%q\n",str,str) //Use%q output with ''
    //Use the functions in strconv package (method 2)
    var num2 = 18
    var num3 = 19.999
    str = strconv.FormatInt(int64(num2),10)
	fmt.Printf("str Type:%T  str=%q\n",str,str) 
    str=strconv.FormatFloat(num3,'f',10,64) //'f': format 10: 10 decimal places reserved 64: floating 64
    fmt.Printf("str Type:%T  str=%q",str,str)
}

The output is:

str Type:string  str="16"
str Type:string  str="18"
str Type:string  str="19.9990000000"
  • Convert string to basic data type
package main
import (
    "fmt"
    "strconv"
	)
func main() {
	var str string = "true"
	var a bool
    a,_ = strconv.ParseBool(str) //strconv. The parsebool (STR) function returns two values (value bool, err, error)
	                             //Because you only need to get value bool and don't want to get err, you use_ ignore
	fmt.Printf("a type:%T a=%v\n",a,a)

	var str2 string = "12345"
	var n int64
	n,_ = strconv.ParseInt(str2,10,64) //The return value type is 64. If you need other int types, you can cast them
	fmt.Printf("n type:%T n=%v\n",n,n)

	var str3 string = "19.999"
	var m float64
	m,_ = strconv.ParseFloat(str3,64)
	fmt.Printf("m type:%T m=%v",m,m)
}

The output is:

a type:bool a=true
n type:int64 n=12345
m type:float64 m=19.999

VIII Pointer

  • Pointer type
    The variable stores an address, and the space pointed to by this address is the value.
    For example: VAR PTR * int = & num
    Get the value pointed to by the pointer type. Use *, for example, * ptr to get the value pointed to by ptr.
package main

import "fmt"

func main() {
	var a int = 10
	fmt.Println("a Address of=",&a)

	var ptr *int = &a 
	//1. ptr is a pointer variable 
	//2. The type of PTR is * int 
	//3. The value of PTR itself is & A
	fmt.Printf("ptr=%v\n",ptr) //The output result is the same as the address of a
	fmt.Printf("ptr Address of=%v\n",&ptr)
	fmt.Printf("ptr Value pointed to=%v",*ptr)
}

The output is:

a Address of= 0xc0000120a8
ptr=0xc0000120a8
ptr Address of=0xc000006030
ptr Value pointed to=10
  • Value type
    Variables store values directly, and memory is usually allocated in the stack.
    Value types include: basic data types, int series, float series, bool, string, array and struct.

  • reference type
    Variables store an address, and the space corresponding to this address is the real storage of data (value). Memory is usually allocated in the heap.
    Reference types include pointer, slice slice, map, pipe chan, interface, etc.

Keywords: Go Back-end

Added by Ganlek on Thu, 27 Jan 2022 05:05:13 +0200