当前位置:网站首页>Go language foundation ----- 03 ----- process control, function, value transfer, reference transfer, defer function
Go language foundation ----- 03 ----- process control, function, value transfer, reference transfer, defer function
2022-07-03 07:36:00 【Mango sauce】
1 Process control
It's just about "for range sentence " This keyword , It's mainly used to traverse , To traverse an array 、slice、map、chan.
for example :
package main
import (
"fmt"
)
func main() {
str := "hello world, China "
for i, v := range str {
fmt.Printf("index[%d] val[%c]\n", i, v)
}
}

2 function
Function is actually mentioned in the previous section .
2.1. Declarative grammar :func Function name ( parameter list ) [( Return value list )] {}
for example
func add(){
}
2.2. golang Function features :
a. Overload is not supported , A package cannot have two functions with the same name .
b. Function is also a type , A function can be assigned to a variable .
c. It could be an anonymous function .
d. Multiple return values .
Examples of functions 1, The formal parameter has a callback function .
package main
import "fmt"
// Define a function pointer , and C/C++ Of typedef equally
type op_func func(int, int) int
func add(a, b int) int {
return a + b
}
func sub(a, b int) int {
return a - b
}
// Define a function , The formal parameter of this function has a callback function
func operator(op op_func, a, b int) int {
return op(a, b)
}
func main() {
var a, b int
add(a, b)
var c op_func // Custom type variables c.
c = add // Assign a function to a variable c.
fmt.Println(add)
fmt.Println(c)
sum := operator(c, 100, 200)
fmt.Println(sum)
}
Examples of functions 2, If the return value of the function is only written return, Will be returned according to the return value declaration of the function .
package main
import "fmt"
func calc(a, b int) (sum int, avg int) {
sum = a + b
avg = (a + b) / 2
return // Although there is no return , But in fact, it will be returned according to the return value declaration above . It's equivalent to a statement :return sum, avg
}
func main() {
sum, avg := calc(10, 20)
fmt.Println("sum: ", sum, ", avg: ", avg)
}

2.3. Function parameter transfer method ( Value passed 、 reference ):
1). Value passed .
2). reference .
Be careful 1: Whether it's value passing , Or by reference , What is passed to the function is a copy of the variable , however , Value passing is a copy of the value . Reference passing is a copy of the address , Generally speaking , Address copying is more efficient . The copy value depends on the size of the copied object , The larger the object , The lower the performance .
And because of the address copy , They will share the same piece of memory , So after the function is modified and returned , Go back to the calling function and use , This variable has also changed .
Be careful 2:map、slice、chan、 The pointer 、interface By default, it is passed by reference .
2.4. Name the return value
Look at the example of the function above 2.
2.5. _ identifier , Used to ignore the return value
func calc(a, b int) (sum int, avg int) {
sum = a + b
avg = (a +b)/2
return
}
func main() {
sum, _ := calc(100, 200)
}
2.6. Variable parameters :
func add(arg…int) int {
//0 Two or more parameters
}
func add(a int, arg…int) int {
// 1 Two or more parameters
}
func add(a int, b int, arg…int) int {
// 2 Two or more parameters
}
Be careful : among arg It's a slice, We can go through arg[index] Access all parameters in turn , adopt len(arg) To determine the number of parameters passed , however len(arg) The scope of is just arg, Do not include parameters that have been determined , For example, the code above "1 Two or more parameters ", Ahead a The formal parameter is not in this length len Range .
for example :
package main
import "fmt"
func add(a int, arg ...int) int {
var sum int = a
for i := 0; i < len(arg); i++ {
sum += arg[i]
}
return sum
}
func concat(a string, arg ...string) (result string) {
result = a
for i := 0; i < len(arg); i++ {
result += arg[i]
}
return
}
func main() {
sum := add(10, 3, 3, 3, 3)
fmt.Println(sum)
res := concat("hello", " ", "world")
fmt.Println(res)
}

3. defer purpose :
1. When the function returns , perform defer sentence . therefore , It can be used to clean up resources .
2. Multiple defer sentence , Follow the first in, last out mode , The same principle as stack .
3. defer Variables in statements , stay defer Its value is determined when it is declared .
3.1 Common operations for cleaning up resources :
// 1 Close the file handle :
func read() {
file := open(filename)
defer file.Close()
// File operations
}
// 2. Lock resource release
func read() {
mc.Lock()
defer mc.Unlock()
// Other operating
}
// 3. Database connection release
func read() {
conn := openDatabase()
defer conn.Close()
// Other operating
}
3.2 defer Example 1:
package main
import "fmt"
// Define a global function variable
var (
result = func(a1 int, b1 int) int {
return a1 + b1
}
)
func test(a, b int) int {
// Here we define a local function variable , So actually test And global variables result It's the same thing
result := func(a1 int, b1 int) int {
return a1 + b1
}
return result(a, b)
}
func main() {
// 1. Call global function variables
fmt.Println(result(100, 200))
var i int = 0
defer fmt.Println(i) // Yes defer The statement of will be executed finally , But the variables used are determined when declared here , So here is the final output :0
defer fmt.Println("second") // First in, then out , So the two one. defer Finally, it must be output :second after , Then the output 0
i = 10
fmt.Println(i)
}

3.3 Example 2:
func f() {
// It's equivalent to executing 5 Time defer, Then according to the situation of first in and last out , So it's output 4 3 2 1 0
for i := 0; i < 5; i++ {
defer fmt.Printf("%d ", i)
}
}

边栏推荐
- PAT甲级 1032 Sharing
- Lucene hnsw merge optimization
- Beginners use Minio
- JUnit unit test of vertx
- 【MySQL 12】MySQL 8.0.18 重新初始化
- 【MindSpore论文精讲】AAAI长尾问题中训练技巧的总结
- Dora (discover offer request recognition) process of obtaining IP address
- Read config configuration file of vertx
- Jeecg menu path display problem
- 2021-07-18
猜你喜欢

Technical dry goods | alphafold/ rosettafold open source reproduction (2) - alphafold process analysis and training Construction

研究显示乳腺癌细胞更容易在患者睡觉时进入血液

Shengsi mindspire is upgraded again, the ultimate innovation of deep scientific computing

为什么说数据服务化是下一代数据中台的方向?

Paper learning -- Study on the similarity of water level time series of Xingzi station in Poyang Lake

TreeMap

技术干货 | AlphaFold/ RoseTTAFold开源复现(2)—AlphaFold流程分析和训练构建

【MySQL 11】怎么解决MySQL 8.0.18 大小写敏感问题
![[coppeliasim4.3] C calls UR5 in the remoteapi control scenario](/img/ca/2f72ea3590c358a6c9884aaa1a1c33.png)
[coppeliasim4.3] C calls UR5 in the remoteapi control scenario

Inverted chain disk storage in Lucene (pfordelta)
随机推荐
IO stream system and FileReader, filewriter
Shengsi mindspire is upgraded again, the ultimate innovation of deep scientific computing
JS monitors empty objects and empty references
Common architectures of IO streams
Analysis of the eighth Blue Bridge Cup single chip microcomputer provincial competition
Summary of Arduino serial functions related to print read
Jeecg menu path display problem
Analysis of the problems of the 7th Blue Bridge Cup single chip microcomputer provincial competition
Web router of vertx
Vertx metric Prometheus monitoring indicators
【LeetCode】4. Best Time to Buy and Sell Stock·股票买卖最佳时机
Industrial resilience
The embodiment of generics in inheritance and wildcards
研究显示乳腺癌细胞更容易在患者睡觉时进入血液
【开发笔记】基于机智云4G转接板GC211的设备上云APP控制
Unified handling and interception of exception exceptions of vertx
Take you through the whole process and comprehensively understand the software accidents that belong to testing
URL programming
【LeetCode】2. Valid Parentheses·有效的括号
Leetcode 198: house raiding