Go language self-study notes (b)

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/96829398

Go language functions:

Function definition format:

func fun(/*参数列表*/)(/*返回值列表*/){
    //函数体
    //返回语句
}

No argument no return value of the function definition and call:

package	main
import "fmt"
func fun(){		
	fmt.Println("函数运行")	
}		
func main(){
	fun()
}

have to be aware of is:

1. The program is executed from the entrance, the function must be defined in order to be called, you need to call a function in the main function: function name ()

2. Custom functions no difference before and after the main function, the function is defined but not called without error.

3. The individual program source code for the function name case no difference

There are no parameters define the return value of the function and call: general argument list

func fun(a int){
	fmt.Println("函数参数",a)
}
func main(){
	fun(100)
}

have to be aware of is:

1. The parameters defined function defined in the function name () is called parameter.

2. The same name can not function / defined repeatedly, and must not require the keyword parameter definition, can not be defined in the parameter list functions in vivo. At the same time, the assignment parameters can only function in the body, can not be placed in the parameter list, otherwise it will error.

Function name (required parameter), the required parameters call function is called passing arguments 3. When the function is called.

4. The parameters are passed only by the argument to the parameter, not the reverse transfer (unidirectional transmission).

Definition of a plurality of function call parameters comprising:

func fun(a int,b int){        //参数类型相同可以简写为(a,b int)
	fmt.Println("函数参数",a,b)
}
func main(){
	fun(100,200)
}

Note that: the parameter list there are several parameters to call when we should pass several parameters, otherwise it will error: not enough parameters to call.

Function definitions and calls have parameters without return value: variable parameter list

func fun(args ...int){
	fmt.Println("函数参数",args)
}
func main(){
	fun(100,200,300)
}

have to be aware of is:

1. Type of variable parameters: ... int like this type called variable parameter types (... type).

2. The argument may be transmitted a plurality of 0-n

3. the indefinite parameters, built-in functions len (args) parameters of the user can read the number of passed.

Uncertain parameters used:

for recycling: in vivo function using the function of the variable parameter list

for i:=0;i<len(args);i++{
	fmt.Printf("参数%d的内容为%d\n",i,args[i])
}

Iteration uses: in vivo using a function in the function of the variable parameter list

for i,data:=range args{
	fmt.Printf("参数%d的内容为%d\n",i,data)
}

have to be aware of is:

1. uncertain parameters must be placed in the last parameter parameter, otherwise error.

func fun(a int,args ...int){}

2. The fixed parameter is a parameter passing necessary, variable parameter transmission parameters according to the needs.

Pass variable parameters: We can be uncertain parameters passed to a function within another function

func myfunc (tmp ...int){	
}
func test(args ...int){
	myfunc(args...)    //全部元素传递给myfunc
	myfunc(args[:2]...)    //args[2]前(不包括)进行传递
	myfunc(args[2:]...)    //args[2]后(包括)进行传递
}
func main(){
    test(1,2,3,4)
}

There are no parameters defined in the function return value:

A single return values ​​have a variety of writing:

A wording:

func myfunc() int {		
	return 100
}

have to be aware of is:

You can not declare the variable name 1. Only a return value, brackets omitted.

2. The function returns the value needed to return the interrupt function and returns the corresponding amount.

Written two:

func myfunc() (result int) {
	return 100
}

At this point we can also play as a return value of a variable name and code optimization are: common side

func myfunc() (result int) {
	result=100
	return 
}

This method is named for the return value, which is a language of the recommended wording Go to clear the main.

Note: The return value returns the entire list, do not write the content after return.

No argument there is the return value of the function call:

func main(){
	var a int
	a=myfunc()    //赋值接受返回值
	b:=myfunc()    //自动推导接受返回值
}

Declare a function without parameters to return multiple return values: Go language is unique, different from other languages ​​returns a single value limitations

Traditional writing:

func myfunc() (int,int,int) {
	return 1,2,3
}

Go language recommended wording:

func myfunc() (a int,b int,c int) {	//也可以写为(a,b,c int)
	a,b,c=1,2,3		//多重赋值
	return 
}

No parameter returns the calling function multiple return values:

func main(){
    a,b,c:=myfunc()
    fmt.Printf("第一个参数:%d\n第二个参数:%d\n第三个参数:%d\n",a,b,c)
}

At this point if the return value output, output format is recommended clearer convenient

There are also return parameter value and call function declaration: two cases of selecting the maximum value of the number of

func maxandmin(a,b int)(max,min int){
	if a>b{
		max=a 
		min=b 
	}else{
		max=b 
		min=a 
	}
	return 
}
func main(){
	max,min:=maxandmin(10,20)
}

At this point, if we want to receive the maximum or minimum value alone, you can also use the anonymous variable to a default return value:

max,_:=maxandmin(10,20)

Ordinary function call flow: a set of nested call - after the first call returns, last-out

package main
import "fmt"
func fun2(x int) (a int) {
	a=x+1
	fmt.Println("函数2运行,当前a的值是", a)
	fmt.Println("函数2运行结束,当前a的值是", a)
	return
}
func fun1(x int) (a int) {
	a=x+1
	fmt.Println("函数1运行,当前a的值是", a)
	a = fun2(a)
	fmt.Println("函数1运行结束,当前a的值是", a)
	return
}
func main() {
	a := 0
	fmt.Println("主函数运行,当前a的值是", a)
	a = fun1(a)
	fmt.Println("主函数运行结束,当前a的值是", a)
}

operation result:

主函数运行,当前a的值是 0
函数1运行,当前a的值是 1
函数2运行,当前a的值是 2
函数2运行结束,当前a的值是 2
函数1运行结束,当前a的值是 2
主函数运行结束,当前a的值是 2

When they find each function to perform a similar function, at this time, we use this feature to rewrite the recursive function call: function calls itself:

package main
import "fmt"
func test(a int) {
	if a == 2 {
		fmt.Printf("递归a=%d\n", a)
		return //终止函数,否则将无限递归
	}
	fmt.Printf("递归a=%d开始\n", a)
	test(a + 1)
	fmt.Printf("递归%d结束\n", a)
}
func main() {
	a := 0
	test(a)
}

operation result:

递归a=0开始
递归a=1开始
递归a=2
递归1结束
递归0结束

Application of recursive function: accumulated digital implementation (1-100)

Traditional Method: Package for loop functions:

func test01() (sum int) {
	for i := 1; i <= 100; i++ {
		sum += i
	}
	return
}
func main() {
	sum := test01()
	fmt.Println(sum)
}

Recursive method:

Reverse cumulative:

func test02(i int) int {
	if i == 1 {
		return 1
	}
	return i + test02(i-1)
}
func main() {
	sum := test02(100)
	fmt.Println(sum)
}

Cumulative positive sequence:

func test03(i int) int {
	if i == 100 {
		return i
	}
	return i + test03(i+1)
}
func main() {
	sum := test03(1)
	fmt.Println(sum)
}

Go Language Functions type:

Traditional methods call the function: function name (parameter list)

func Add(a,b int ) int {
	return a+b
}
func minus(a,b int) int{
	return a-b
}
func main(){
    result:=Add(1,1)
}

We can also be seen as a function of a data type by type a name to the function from the function type, but have the same requirements and function parameter list and return values ​​can be assigned by function type variable.

type FuncType func(int,int)int    //没有函数名字以及大括号,FuncType是一种自定义函数类型

Function type variable definition and assignment:

func main(){
    var fTest FuncType    //声明一个函数类型变量fTest
    fTest = Add    //将函数入口赋值给变量
    result:=fTest(1,1)    //等价于result:=Add(1,1)
}

Note that: the function name is the entry address of the function, a function similar to the function pointer type c language

Mainly polymorphic thought: callback - function parameter is a function of a type

Calculation function realized four operations:

func Calc(a,b int, fTest FuncType) (result int){
	result=fTest(a,b)		//函数没有实现
	return 
}

Note Note that, at this time fTest specific function did not materialize. For this calculation function, the prior frame, and then implement the functions. It reflects the polymorphism: a variety of forms call, call the same interface, you can achieve different functions - the four operations.

Calculation function is called:

func main(){
    result:=Calc(1,1,Add)
}

Use a dictionary or switch call functions similar to the Python here

The advantages of this method:

Without first defining and implementing the call, this function can be called to reserve a space, do not need to immediately implement a function parameter passing, to function more space to develop, has a unique advantage to use more function function. Traditional writing is no way to achieve polymorphism, the need to achieve immediate function.

Anonymous functions and closures: no function name, you can capture external variables.

Anonymous function definition:

Definition and manually call:

func main(){
    f1:=func(){		//自动推导类型,较为常用
        fmt.Println("匿名函数")
    }
    f1()
}

Alias ​​function call: This method is not used

type FuncType func()
var f2 FuncType
f2=f1
f2()

Define anonymous functions and automatically call:

func(){
    fmt.Println("匿名函数")
}()		//此()代表自动调用此匿名函数--传递参数括号

Anonymous manual function calls with parameters:

f3:=func(i,j int){
    fmt.Println("匿名函数参数:",i,j)
}
f3(10,20)

Anonymous function with parameters automatically call:

func(i,j int){
    fmt.Println("匿名函数参数:",i,j)
}(10,20)

Anonymous function with parameters and return values ​​automatically call:

x,y:=func(i,j int)(max,min int){
    //函数体,将参数最大值赋给max,参数最小值赋给min。详细代码省略
    return
}(10,20)

Closure capture characteristics of external variables: the variables may be captured outside the closure interior and modifying variable values, also external modification effect

func main(){
    a:=10
    func(){
	    a=11
	    fmt.Println(a)
    }()
    fmt.Println(a)
}

Closure reference capture external variables:

Normal function:

func test01 () int{
	var x int
	x++
	return x*x
}

Each call to this function is the main function, the result returned is 1: each call, the same result. Because x allocate space only when this function is called and initialized to 0, the function call is completed x automatically released.

If let the function return value is an anonymous function that returns a function type: Closures

func test02() func() int{
	var x int
	return func() int{
		x++
		return x*x
	}
}
func mian(){
    f:=test02()
}

In this case, the function return value is an anonymous function returns a function type, anonymous function to call returned by f - closure function.

This function is called each time a function, the result returned is different 1,4,9,16 ....

We can conclude that: the closure does not care about the capture of variables and constants is beyond the scope, as long as the closures are still using these quantities, they will continue to exist and will not be released to reset. Namely: the life cycle of the bag closed variable is not determined by his scope.

To delay calling Keywords defer: only on the internal function, you can do some clean-up action on and off, will run until the end of the main function.

func main(){
	defer fmt.Println("打印语句2")
	fmt.Println("打印语句1")
}

At this time, the output is:

打印语句1
打印语句2

When multiple defer common action: first statement does not defer the execution, calls to defer the implementation of the press after the first write. Functions like the middle of error does not lead to defer execution of an interrupt.

defer conjunction with the anonymous function:

defer func(a,b int){
    fmt.Println("匿名函数参数:",a,b)
}(100,200)

Note that: If this function is passed the order parameter, passing parameters is not affected in the sequential structure of the entire program, but was only such functions will be called before the end of the main function.

Gets command line arguments languages ​​Go:

package main
import "os"
func main(){
    list:=os.Args
}

At this time, the number of the user may be acquired through the built-in function input parameters:

n:=len(list)

But it notes that: to accept user parameters are passed to accept the character string, run the command can also be regarded as a parameter.

At the same time if we want to get the user's parameters can also be in the following ways:

Methods for loop:

for  i:=0;i<n;i++{
    fmt.Printf("用户第%d个参数:%d\n",i,list[i])
}

Iterative method:

for i,data:=range list{
    fmt.Printf("用户第%d个参数:%d\n",i,data)
}

Go language variable rules:

Local variables: {} is defined in or belongs to a block of statements such as if, for other is a local variable (scope scope, variable), only effective in the braces or a certain block. Execution to define local variables are allocated space, out of scope automatically released.

Global variables: variables defined in the outer function is a global variable, can be used anywhere in the program.

The following rules apply when a local variable with the same name as a global variable: allows you to define different scopes variables of the same name, but using variables take the principle of proximity, variable scope of the variables used in the statement where the variable is a variable that is nearest.

Go language workspace:

1.Go language code must be placed in the work area, or can not import the package.

2. The package has a modular more conducive to the maintenance and the calling code.

3. The source code must be placed in the src directory.

4. The package will be introduced from the introducing GOPATH.

The method of introducing the package:

Traditional method:

import "fmt"
import "os"

Common wording:

import(
	"fmt"
	"os"
)

(Dot) Operation:

import . "fmt"

Using this method, the calling function without going through the package name, but due to personal habits may result in duplicate names.

Alias ​​method:

import io "fmt"

Using this method, fmt when calling function can be changed to io.

Ignore bag method:

import _ "fmt"

This method is used in order to introduce the packet, but the function is not used in the packet, only theft init function in the packet (described later have).

init function introduction: init function equivalent to the initialization function

When introduced into the bag, the package is executed again after the function init performs main functions.

If the init function itself has, is introduced to the init packet, the execution itself init, and finally execute main.

Go language project management:

The same folder under the project management:

1 min .. Programming files (multiple source files), must be placed in the project directory src directory (self-written).

2. Set GOPATH environment variable.

Computer Properties> Advanced System Settings> Environment Variables> System Variables GOPATH set up within the src directory of the project folder (directory project src directory)

3. The same directory as the package name must be the same, only one program entry.

src内:main.go(package main) test.go(package main)

4.go env go see related environmental path.

5. call other files in the same directory functions can be called directly without having to reference the name of the package.

Different level directory folder under the project management:

1. Different package different directory name

src内:main.go(package main)

In src / cacl: calc.go (package calc)

2. invoke different functions inside the package formats: package name function name () need to import the package name introduced

3. The temporary configuration: liteide compiler to configure custom project src directory GOPATH

4. If you call another package function, the function name is lowercase can not be invoked, the function call must be capitalized.

If you have more than one file or several packages:

1. Configure GOPATH environment variables, configuration src directory absolute path --- the project folder.

2. automatically generate bin and pkg, you need to use go install command.

3. placed GOBIN

In the project directory:

1. Create GOBIN in the system variable, the variable value compared to the bin directory under the project directory.

Go install using the command line under 2. project src directory, and automatically generate bin pkg.

src: storing source code

bin: to store the executable

pkg: storage platform-dependent library

Guess you like

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