[seven day introduction to Go language] program structure & & data type | calf knife test the next day

Posted by allenmak on Tue, 04 Jan 2022 04:23:15 +0100

1. Program structure

1.1 name

If an entity name is declared in a function, it is only valid locally in the function. If declared outside the function, it will be visible to all source files in the package.

The case of the first letter of an entity determines whether its visibility spans packages. If the name starts with a capital letter, it is exported, which means that it is visible and accessible to outsourcing and can be referenced by other programs outside its own package.

Capital is OK!


And Go language often uses hump style naming

func main() {
	FanOne := "666" //Large hump (note! Generally, small humps and local variables are used inside functions. Large humps are generally used for function naming and need to be exported externally)
	fanOne := "666" //Small hump

Of course you can use underline, for example, but I still prefer hump style~

1.2 declaration

go language can declare variables through var
var variable name type

For example:

func main(){
	var fanOne string 
	var xiaoSheng int
	var a,b,c = true , 6.6 , "fanOne" //bool ,float , string

Of course, you can also use:=

for example

func main(){
	fanOne:="666" //String string
	xiaoSheng := 666  //int integer
	a,b,c := true , 6.6 ,"fanOne"  //bool ,float , string

1.3 notes

Can use

//Single-Line Comments 

multiline comment 

1.4 single and double quotation marks

func main(){
	var d rune
	d = '1'
	a := 'a'
	b := "a"
	c := `'a'':"b"`  //You can enclose single quotation marks and double quotation marks
	fmt.Printf("%T\n",d)	 // int32
	fmt.Printf("%T\n",a)	 // int32
	fmt.Printf("%T\n",b)	 // string
	fmt.Printf("%T\n",c)  	 // string

1.5 output

//Println comes with line feed Printf formatted output 

2. Data type

2.1 integer

Integer data can be divided into two types, signed and unsigned

  • Signed: int, int8, int16, int32, int64

  • Unsigned: uint, uint8, uint16, uint32, uint64, byte

In addition, rune is an alias of int32

Under the condition of ensuring the correct operation of the program, try to use the data type with small space

  1. The difference between integers with different digits is that it can save the size of the integer number range;
  2. Signed types can store any integer, while unsigned types can only store natural numbers
  3. The sizes of int and uint are related to the system. A 32-bit system represents int32 and uint32. If it is a 64 bit system, it represents int64 and uint64
  4. byte, similar to uint8, is generally used to store a single character

2.2 floating point

There are float64 and float32

  • The accuracy of float64 is more accurate than that of float32
  • If we want to save a high-precision number, we should choose float64

The storage of floating-point type is divided into three parts: sign bit + exponential bit + trailing digit. In the storage process, the precision will be lost

The float type of Go defaults to float64

2.3 plural

There are complex64 and complex128, which are respectively composed of float32 and float64. The built-in complex function creates the complex according to the given real part and imaginary part, while the built-in real function and img function extract the real part and imaginary part of the complex respectively:

var x complex128 = complex(1,2) //1+2i
var y complex128 = complex(3,4) //3+4i
fmt.Println(x*y) 		//-5+10i
fmt.Println(real(x*y))  //-5
fmt.Println(imag(x*y))  //10

Of course, we can do the same

x := 1 + 2i
y := 3 + 4i

2.4 Boolean

There are only two possibilities: true or false

var fanOne true
var xiaoSheng false

2.5 string

func main(){
	fmt.Println(len(s)) //6
	fmt.Println(s[:3])  //Fan
	fmt.Println(s[1],s[2]) // 97 110

String splicing

func main(){
	b := "666"
	y := s + b
	fmt.Println(y) //FanOne666

String to int

num,err:=strconv.Atoi("666")//num is an integer

int to string

str := strconv.Itoa(666) //str is a string

2.6 constants

const a = 666
fmt.Println(a) //666

2.7 array

var a [3]int //Array of 3 integers
for i , v := range a {
var fan [3]int{1,2,3}
var one [3]int{1,3}
t := [...]int{1,2,3} //ellipsis
fmt.Printf("%T",t)	 //[3]int

The length of array in go language is fixed, so array has its limitations in some scenarios
The existence of slice solves the problem of limited array length. Slice can be regarded as an array that can be automatically expanded, but it is still different from array.

2.8 slicing

You can create and initialize slices by making or slice literal, or directly create slices by using existing arrays or slices (reference types (slice, map, chan) in Go language cannot be initialized with new).

When using make, you need to pass in a parameter to specify the length of the slice. If only the length is specified, the capacity and length of the slice are equal. You can also pass in two parameters to specify the length and capacity respectively. It is not allowed to create slices with a capacity less than the length.

// If make passes in only one parameter specifying the length, the capacity and length are equal. The following output: "len: 10, cap: 10"
s := make([]int, 10)
fmt.Printf("len: %d, cap: %d\n", len(s), cap(s))

// make incoming length and capacity. The following output: "len: 10, cap: 15"
s := make([]int, 10, 15)
fmt.Printf("len: %d, cap: %d\n", len(s), cap(s))

// It is not allowed to create slices with a capacity less than the length. The following statement will report an error when compiling: "len larger than cap in make([]int)"
s := make([]int, 10, 5)

The slice is declared by the slice literal.

// The slice is declared by literal, and its length and capacity are 5. The following output: "len: 5, cap: 5"
s := []int{1, 2, 3, 4, 5}
fmt.Printf("len: %d, cap: %d\n", len(s), cap(s))

// The index can be used to give the required length and capacity when declaring the slice.
// Create a slice with a length and capacity of 100 by specifying an element with an index of 99
s := []int{99: 0}

The method to create a slice based on an existing array or slice is: s: = basestr [low: high: max], low specifies the start element subscript, high specifies the end element subscript, and max specifies the element subscript to which the slice can grow. These three parameters can be omitted. Low omission starts with subscript 0 by default, high omission is the subscript of the last element by default, and max omission is the capacity of the underlying array or slice by default (note that max cannot be less than high here). In this way, the calculation method of slice length and capacity is:

len = hith - low
cap = max - low
s1 := baseStr[1:3:10]
fmt.Printf("len: %d, cap: %d\n", len(s1), cap(s1)) // len: 2, cap: 9

s2 := baseStr[1:3]
fmt.Printf("len: %d, cap: %d\n", len(s2), cap(s2)) // len: 2, cap: 9

s3 := baseStr[:3]
fmt.Printf("len: %d, cap: %d\n", len(s3), cap(s3)) // len: 3, cap: 10

ss1 := s1[2:5]
ss2 := s1[3:8]
fmt.Printf("len: %d, cap: %d\n", len(ss1), cap(ss1)) // len: 3, cap: 7
fmt.Printf("len: %d, cap: %d\n", len(ss2), cap(ss2)) // len: 5, cap: 6

Add can use append

// Create an integer slice
// Its length and capacity are 5 elements
slice := []int{1, 2, 3, 4, 5}

// Create a new slice
// Its length is 2 elements and its capacity is 4 elements
newSlice := slice[1:3]

// Use the original capacity to allocate a new element
// Assign a value of 60 to the new element
newSlice = append(newSlice, 6)

fmt.Printf("slice: %v\n", slice)       // slice: [1 2 3 6 5]
fmt.Printf("newSlice: %v\n", newSlice) // newSlice: [2 3 6]

2.9 map

A Map is an unordered collection of key value pairs. The most important point of Map is to quickly retrieve data through key. Key is similar to index and points to the value of data.

Map is a collection, so we can iterate it like iterating arrays and slices. However, the map is unordered, and we cannot determine its return order, because the map is implemented using a hash table.


/* Declare variables. The default map is nil */
var map_variable map[key_data_type]value_data_type
/* Using the make function */
map_variable := make(map[key_data_type]value_data_type)
	var fan map[string]string //Create collection 
	fan = make(map[string]string)
	//map insert key value pair
	fan [ "One" ] = "666"
	fan [ "Four" ] = "999"
	//Use key output
	for value := range fan {
		fmt.Println(value, "is", fan [value])
	//See if the element exists in the collection
	val, ok := fan [ "Two" ] //If it is determined to be true, it exists, otherwise it does not exist
	if ok {
		fmt.Println("fanTwo is", val)
	} else {
		fmt.Println("fanTwo not exist")

The delete() function is used to delete the elements of the collection. The parameters are map and its corresponding key.
You can delete using the delete method

delete(fan , "One")

2.10 structure

Structure definition requires type and struct statements. Struct statement defines a new data type with one or more members in the structure. The type statement sets the name of the structure. The format of the structure is as follows:

type Person struct{
	name string
	age int
	sex string
func main(){
	person := Person{  //initialization
		name: "fanOne",
		age:  16,
		sex:  "male",
	fmt.Println(person.name)  //quote

2.11 JSON

type Person struct{
	Name string `json:"name"` //Serialize to string type
	Age int	`json:"age"`
	Sex string `json:"sex"`
func main(){
	person := &Person{} //Create an object
	var data = `{"name":"fanOne","age":"11","sex":"male"}`
	_ = json.Unmarshal([]byte(data), &person)  //This data is serialized into the structure of person and passed into it

3. Process control

3.1 conditional statements

func main(){
	x :=1 
	if x == 1 {
	} else {

3.2 selection statement

	switch i {
	case 0:
	case 1:
	case 2:
	case 3:
	case 4, 5, 6:
		fmt.Printf("4, 5, 6")

3.3 circular statements

	sum := 0
	for i := 0; i < 10; i++ {
		sum += i
	s := [3]int{1,2,3}
	for _,item := range s{


Xiaosheng Fanyi, looking forward to your attention.

Topics: Go