Go language self-study notes (c)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_18800771/article/details/97130292

Go language in complex type:

Pointer: Each variable has two data, one memory variable, two variables, i.e., the memory address tag.

We are normal variable output of memory:

var a int = 1
fmt.Println(a)

If we need to manipulate pointers, addresses the need for the operation, i.e. memory tags: & a (output format occupying% p)

fmt.Println(&a)

Save int variable address pointer type needs * int, if you save type * int address required ** int type pointer.

var p *int = &a    //指针变量指向谁就把谁的地址赋值给指针变量,p是*int类型指向int类型变量
*p = 10    //为指针所指向的变量赋值

Note that: not p * p memory operation, but the memory pointed to by p, is equivalent to the operation of a.

Go to retain the language pointer, but the other turned into different languages:

1. The default value of the pointer is nil, NULL is not constant.

2. The operator "&" take the value address, "*" to access the target object through the pointer.

3. does not support pointer arithmetic does not support "->" operator, with direct access to the target member. "."

Do not operate without legal point of Memory: uninitialized or assignment (nil) pointer, otherwise it will error.

To solve this problem, we can generate a space for memory operations with new () function, similar to the dynamic allocation of space, but does not need to consider the release of the Go language space, has its own garbage collection, or do not care about the life cycle of how to delete .

p=new(int)        //赋值
q:=new(int)        //自动推导

Used in conjunction with the function pointer:

Common variable as a function of the parameters: value of the variable by exchanging the function

func swap(a,b int){
    a,b=b,a
}
func mian(){
    a,b:=10,20
    swap(a,b)
}

By this method, since different variable scope, different definitions, there results: Custom Function internal variable value has exchanged, were worthy transmission, but not the exchange value of the variable in the main function.

Address delivery:

func swap(p1,p2 *int){
    *p1,*p2=*p2,*p1
}
func mian(){
    a,b:=10,20
    swap(&a,&b)
}

By this method, the ex who exchanged the memory of two variables, the main function being to achieve a variable worthy exchange.

Go array of language: the same type of simplified declaration and initialization of operation, is a collection of the same type.

Array definition:

var arr [50]int        //50代表数组的容量,下标从0-len()-1

have to be aware of is:

1. The number of elements in the array must be a constant.

2. array subscripting from 0 to len () - 1.

Manual assignment and print array:

Use a for loop and print the assignment:

for i:=0;i<len(arr);i++{
    arr[i]=i
    fmt.Printf("arr[%d]=%d",i,arr[i])
}

You can also use an iterative print:

for i,data:=range arr{
    fmt.Printf("arr[%d]=%d",i,data)
}

You can also use the direct printing:

fmt.Println(arr)

A single array element assignment:

arr[10]=1        // 10是下标,这时的下标可以使用变量或者常量

Initialize the array: a statement that assignment

All initialization:

var arr [5]int=[5]int{1,2,3,4,5}

Part of the initialization:

arr:=[5]int{1,2,3}    //推荐使用自动推导类型,没有初始化的元素自动赋值为0

Specified element initialization:

arr:=[5]int{2:10,5:20}

Two-dimensional array: How many square brackets is a few-dimensional array, how many layers to operate on a cycle.

Two-dimensional array assignment and printing:

for assignment and print circulation:

var arr [3][4]int
k:=0
for i:=0;i<3;i++{
    for j:=0;j<4;j++{
        a[i][j]=k++
        fmt.Printf("a[%d][%d]=%d\n",i,j,a[i][j])
    }   
}

Direct printing:

fmt.Println(arr)

Derivation and Automatic Initialization: similar to nested arrays, each array is a new abscissa.

arr:=[2][2]int{{1,2},{3,4}}

It can also be part of the initialization:

arr:=[2][2]int{1:{1,2}}

An array of comparison and assignment: compare with only == or = returns a Boolean variable!. The same array can only compare each element type is not the same. Meanwhile, the same type of arrays can also be assigned as arr1 = arr2.

Using random numbers: the need to set seed and generates random numbers.

package main
import "math/rand"
import "fmt"
func mian(){
    rand.Seed(123)    //设置种子为123
    fmt.Println(rand.Int())    //产生随机数
}

But note: if you run a seed parameter as a random number generated by the program are the same.

Seed time: time as a native seed.

package main
import "math/rand"
import "time"
func mian(){
    rand.Seed(time.Now().UnixNano())    //设置时间种子,以当前系统时间作为种子参数
 }

We can then generate random numbers within a certain range:

rand.Intn(100)+0        //在0-100范围内产生随机数

Principle bubble sort: comparison of two adjacent sorting elements, a maximum of n-1 row ordering.

package main

import "fmt"
import "math/rand"
import "time"

func main() {
	rand.Seed(time.Now().UnixNano()) //设置时间种子
	var a [10]int
	n := len(a)
	for i := 0; i < n; i++ {
		a[i] = rand.Intn(100) //生成100以内随机数
	}
	fmt.Println(a)
	//冒泡排序,相邻两元素比较排序,升序
	var b bool = true		//增加判断器以优化代码效率
	for i := 0; b == true && i < n-1; i++ {
		b = false
		for j := 0; j < n-1-i; j++ {
			if a[j] > a[j+1] {
				b = true
				a[j], a[j+1] = a[j+1], a[j]
			}
		}
	}
	fmt.Println("排序完成\n", a)
}

An array of function parameters: the array of function parameter is a value passed, each element of the parameter set is shaped solid parameter groups.

func modify(arr [5]int){        //形参的数组是由实参数组复制来的
    arr[0]=20
    fmt.Println(arr)
}
func main(){
    arr:=[5]int{1,2,3,4,5}
    modify(arr)
}

Array pointer of function parameters: the transfer address, the array pointer points to an array of p, p * is the real memory pointed to i.e. parameters arr.

func modify(p *[5]int){
    (*p)[0]=20
    fmt.Println(*p)
}
func main(){
    arr:=[5]int{1,2,3,4,5}
    modify(&arr)
}

Size of the array is fixed, transmission must be complete when the parameter passing, and it introduces the concept of functional sections to compensate for the disadvantages of the array. At the same time slice can be understood as a dynamic array of variable length. Slices are not specified length, cut from the array.

Slice initialization:

a:=[...]int{1,2,3,0,0}    //中括号内可以省略...

Slice and an array of differences:

 

1. Array [] is fixed to a constant length, the length can not be modified, the length and volume are constant.

2. Section [] is empty or ..., and the capacity of the sections may not be a fixed length.

3.append (s, 11) elements can be added to the end sections 11 s.

Create a slice:

Automatic Derivation also initializes:

s1:=[]int{1,2,3,4,5}

Means make function initializes: Format: make (slice type, length, volume)

s2:=make([]int, 5, 10)        //切片容量可以不指定,默认容量与长度相同

Slice taken: fundamental form: s: = a [low: high: max]

s:=a[0:3:5]

Built-in functions: len (s) slices print length, cap (s) slices printing capacity.

low: the subject of the next slice starting point

high: Slice at the end of the subject (not included)

Slice length len = high-low

Slice cap = max-low capacity

The same manner as the operation of the array: an individual operating elements within the slice

data:=array[1]

 Sections taken on the array:

array:=[]int{1,2,3,4,5,6,7,8,9}
s1:=array[:]    //[0:len(array):len(array)]不指定,默认容量与长度相同
s2:=array[3:6:7]    //从array[3]开始到array[5],长度是3,容量是4
s3:=array[:6]    //从0开始取6个元素,长度和容量都是6,此方法最为常用
s4:=array[3:]    //从array[3]开始,取到结尾
s5:=array[2:5]    //从array[2]开始,取3个元素

需要注意的是:切片指向底层数组,在对某个切片元素重新赋值时,无论切片经过多少次重切,切片所指向的最底层数组的相应元素也会跟着被重新赋值,改变。

切片的append追加函数:自动扩容,一旦超过原底层容量,容量通常以两倍的容量重新分配底层数组并复制数据。

append(s,1)    //在切片s末尾添加元素1

切片的copy函数:对某一切片的前几位用原切片做覆盖。copy(目的切片,原切片)

copy(s1,s2)    //将s2替换到s1的前几位

切片做函数参数:引用传递,传递方式与数组值传递相同,但不会完整传递,只会传递所需的某个元素。

产生随机数:产生四位随机数。

传统方法:

rand.Intn(10000)    //产生随机数通过if判断是否大于等于1000

推荐方法:

rand.Intn(9000)+1000    //1000是四位数最小值,9000+1000是四位数最大值(不包含)

切片保存数字的每一位数(4位):可以通过数字的取商‘/’与取余‘%’配合使用,取出数字每一位并追加给切片或给切片元素赋值,如:

s[0]=2514/1000    //求千位
s[1]=(2514%1000)/100    //求百位

Go语言中的map:键值对类型key-value 格式:map[key类型]vale类型{}

需要注意的是:

1.map的key-value是对应的,key不能出现重复。

2.map的打印和返回时无序的。

3.切片与函数不能作为key值。

4.几乎任何类型都可以作为value值。

5.map只有长度没有容量。

map的定义:

直接定义:

var m1 map[int]string        //key为int,value为string

通过make函数定义:

m2:=make(map[int]string)
m3:=make(map[int]string,10)    //指定长度:只是预先分配空间,但没有存数据,长度仍是0

map的初始化:

m:=map[int]string{1:”mike”,2:”tom”,3:”jack”}	//常用,键值一定是唯一的

map的赋值:

m[1]=”go”    //为已经存在的key值赋值--修改value
m[5]=”stop”    //新增key,下标超出分配空间,会自动扩充长度:不存在key值则追加,map底层自动扩容

map的遍历:

for key,value:=range m{}    //遍历结果是无序的

判断key是否存在:

value,info:=m[1]     //info返回布尔类型用来判断key:1是否存在

删除key键值:

delete(m,1)    //删除m中key:1

map做函数参数声明及调用:引用传递,地址传递。

func fun(m map[int]string){
}
func main(){
    fun(m)
}

Go语言的结构体类型:

结构体的定义:与自定义函数同级,定义在主函数之外。

type Student struct{
    id int
    name string
    sex byte
    age int
    addr string
}

声明结构体变量:

var s1 Student = Student{1,"tom",'M',18,"北京"}    //顺序初始化,每一个成员都要初始化
s2: = Student{name:"jack",age:20}    //部分指定成员初始化,没有初始化成员自动赋值为0

结构体指针变量初始化:声明时加“&”,使用/打印时加“*”但*可有可无。打印可以使用可以直接打印。

var p1 *Student=&Student{1,"tom",'M',18,"北京"} 
p2:=&Student{name:"jack",age:20}

结构体成员的使用:操作程序需要用到 . 运算符。

普通变量:

s1.id=10086
s1.name="zx"
s2.age=18
s2.addr="天津"

指针变量:指针有合法指向后才能操作成员。

var s Student        //先定义普通结构体变量
var p *Student        //再定义指针变量指向s保存其地址
p=&s

通过指针操作成员变量时:以下两种语句完全等价,与其他语言不同,都只能运用 . 运算符。

p.id        //推荐写法
(*p).id

new函数创建空间:

p:=new(Student)

Go语言中结构体的比较:与数组比较相类似,只能用==和!=运算符,返回布尔类型。

结构体赋值:同类型的结构体可以相互赋值。

结构体作为函数参数的使用:

值传递:同名不同作用域的函数声明以及调用。

func fun (s Student){
}
func main(){
    fun(s)        //值传递,实参不会跟着实参一起改变
}

地址传递/引用传递:

func fun(p *Student){
}
func main(){
    fun(&s)        //引用传递,参数跟着函数内部改变
}    

可见性规则:

如果想使用其他包的函数、结构体类型、结构体成员。函数名,类型名,结构体成员变量名的首字母必须大写。如果首字母是小写,则只能在同一个包里面使用。

Guess you like

Origin blog.csdn.net/qq_18800771/article/details/97130292