Golang learning path 4-function/import package/command line parameters/defer, etc.

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


1. Function

The function declaration begins with the func keyword, and the function, that is, the code block, can be input and output. The format is:

func name(parameter) (result-list){
    
    
    //body
}

1. Define functions

1.1 Single return value function

// 单返回值函数,返回值定义可以不需要括号
func add(a, b int) int{
    
    
	return a + b
}

1.2Multiple return value functions

func ppl(a int, b int) (int, bool) {
    
    
	c := a + b
	isBool := false
	if a*2 > c {
    
    
		isBool = true
	}
	return c, isBool
}

1.3 Specify the return value variable name function, which can be returned directly

func ppl1(a int, b int) (number int, isBool bool) {
    
    
	number = a + b
	if a*2 > number {
    
    
		isBool = true
	}
	return
}

1.4 Parameter variable function

// 参数可变函数
func ppl3(nums ...int)int{
    
    
	fmt.Println("len of nums is : ", len(nums))
	sum := 0
	for _, v := range nums{
    
    
		sum += v
	}
	return sum
}

Complete code:

package main

import "fmt"

func main() {
    
    
	a := 2
	b := 2
	fmt.Println(ppl(a, b))
	fmt.Println(ppl1(a, b))
	fmt.Println(ppl2(a, b))
	fmt.Println(ppl3(a, b))
}
// 单返回值函数,返回值定义可以不需要括号
func ppl2(a int, b int) bool {
    
    
	number := a + b
	if a*2 > number {
    
    
		return true
	}
	return false
}
// 可多个形参,多个返回值需要定义使用括号,逗号分隔
func ppl(a int, b int) (int, bool) {
    
    
	c := a + b
	isBool := false
	if a*2 > c {
    
    
		isBool = true
	}
	return c, isBool
}
// 当返回值有定义变量名称时,可以直接return
func ppl1(a int, b int) (number int, isBool bool) {
    
    
	number = a + b
	if a*2 > number {
    
    
		isBool = true
	}
	return
}
// 参数可变函数
func ppl3(nums ...int)int{
    
    
	fmt.Println("len of nums is : ", len(nums))
	sum := 0
	for _, v := range nums{
    
    
		sum += v
	}
	return sum
}

2.Anonymous function

Anonymous function, called directly without a function name

// 匿名函数
func() {
    
    
	fmt.Println("匿名函数...")
}()

3.init function

  • init function has no parameters and return value
  • The init function does not allow users to call it explicitly
  • The init function is generally used for initialization
package main

import (
	"fmt"
	_ "ppl-golang/1-base/01/9-import/sub" // 仅会调用包的init函数
)

/*
1.init函数没有参数和返回值
2.init函数不允许用户显式调用
3.init函数一般用作初始化
*/
func init() {
    
    
	fmt.Println("this is my init 111111")
}

func init() {
    
    
	fmt.Println("this is my init 222222")
}
func main() {
    
    
	//init()	不能这样调用
}

Insert image description here


2. Import package import

1. Import the package using the keyword: import

But what is a bag? Can be understood as a functional module

  • Public: Open call (public) package functions start with a capital letter, otherwise they cannot be called;
  • Private: not open to external calls (private only uses lowercase letters for package functions under the same package name);
// 包
package sub

// 公有
func Sub(a, b int) int {
    
    
	return a - b
}
// 私有
func low()  {
    
    
	
}

2. Reference package

package main

import (
	"fmt"
	// . 表示包名下所有函数不推荐直接用,容易出现重复函数名冲突
	. "ppl-golang/1-base/9-import/add"
	// 导入包可在前面空格+重命名,如下:ppl
	ppl "ppl-golang/1-base/9-import/sub"
)
func main() {
    
    
	// 调用:包名.函数名
	sum := Add(10, 5)
	sub1 := ppl.Sub(sum, 2)
	fmt.Println(sub1)
}

3. Command line parameters

1.os.Args gets command line parameters

os.Args, the first parameter is the currently executed program, for example, Windows is xx.exe,
so the second parameter is the customized parameter, and the slice is 1, as shown in the following code cmds[1]

package main

import (
	"fmt"
	"os"
)
func main() {
    
    
	// 命令行参数
	cmds := os.Args
	fmt.Println("cmds个数=", len(cmds), "(需要>=2)")
	if len(cmds) < 2 {
    
    
		return
	}
	for k, cmd := range cmds {
    
    
		fmt.Println("key:", k, " cmd:", cmd)
	}
}

2. Initial test of command line parameters

The switch judges that the values ​​are equal, and a break is added by default. If you want to continue to penetrate, add the keyword: fallthrough

package main

import (
	"fmt"
	"os"
)

func main() {
    
    
	// 命令行参数
	cmds := os.Args
	fmt.Println("cmds个数=", len(cmds), "(需要>=2)")
	if len(cmds) < 2 {
    
    
		return
	}

	switch cmds[1] {
    
    
	case "hello":
		fmt.Println("cmds[1] is hello")
	case "word":
		// 如果值相等,默认会加了 break,如果想继续穿透加上关键字:fallthrough
		fmt.Println("cmds[1] is word")
		fallthrough
	default:
		fmt.Println("cmds[1] is default")
	}
}

Insert image description here


4. Label

Use less, just understand it

package main

import "fmt"

func main() {
    
    
	// 标签名称是自定义
LABEL1:
	for i := 0; i < 2; i++ {
    
    
		for j := 0; j < 5; j++ {
    
    
			if j == 3 {
    
    
				/*
					goto LABEL1:i每次进入此标签被重置值
					continue LABEL1:i每次进入此标签会记录上次的值(状态)
					break LABEL1:直接结束指定位置的循环
				*/
				//goto LABEL1
				//continue LABEL1
				break LABEL1
			}
			fmt.Println(i, j)
		}
	}
	fmt.Println("over!")
}

5. const iota enumeration

const iota enum

package main

import "fmt"

const (
	/*
		1.iota是常量组计数器
		2.iota从0计数,每行递增1,同一行多个只算一次
		3.每隔常量组是独立的,如果再定义一个const会重iota新计数,不想被重新计数+1
	*/
	name         = iota
	age          = iota
	work         = iota
	single                    // 未赋值,默认与上一个常量值相同
	work1, work2 = iota, iota // iota计数同一行多个只算一次
)

func main() {
    
    
	fmt.Println(name)
	fmt.Println(age)
	fmt.Println(work)
	fmt.Println(single)
	fmt.Println(work1)
	fmt.Println(work2)
}

Insert image description here


6. defer (delay)

The defer keyword is used to modify statements and functions to ensure that this statement is executed when the current stack exits. It
is exactly the opposite of the init function. The init function is executed before and defer is executed after, similar to python reading a file with open().

package main

import (
	"fmt"
	"os"
)

func main() {
    
    
	/*
		defer 延迟用于修饰语句、函数,确保这条语句在当前栈退出时执行
		一般用于清理工作,解锁、关闭文件操作,类似python读取文件 with open()
	*/
	fineName := "1-base/02/4-defer延迟.go"
	redFine(fineName)
}

func redFine(fileName string) string {
    
    
	f, err := os.Open(fileName)
	defer f.Close()	// 在当前栈退出时执行关闭文件
	if err != nil {
    
    
		fmt.Println("打开文件失败:", fileName)
	}
	buf := make([]byte, 1024)
	f.Read(buf)
	fmt.Println(string(buf))

	// 多个defer,执行顺序为倒序
	defer fmt.Println(1111111)
	defer fmt.Println(2222222)

	// 匿名函数
	defer func() {
    
    
		f.Close()
		fmt.Println("匿名函数关闭文件...")
	}()
	defer fmt.Println(33333333)
	return string(buf)
}

Insert image description here
End

Guess you like

Origin blog.csdn.net/qq_42675140/article/details/127594092