当前位置:网站首页>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)
}
}

边栏推荐
- Margin left: -100% understanding in the Grail layout
- [coppeliasim4.3] C calls UR5 in the remoteapi control scenario
- Traversal in Lucene
- 项目经验分享:实现一个昇思MindSpore 图层 IR 融合优化 pass
- Reconnaissance et détection d'images - Notes
- 项目经验分享:基于昇思MindSpore,使用DFCNN和CTC损失函数的声学模型实现
- 技术干货|昇思MindSpore创新模型EPP-MVSNet-高精高效的三维重建
- 你开发数据API最快多长时间?我1分钟就足够了
- [Development Notes] cloud app control on device based on smart cloud 4G adapter gc211
- Comparison of advantages and disadvantages between most complete SQL and NoSQL
猜你喜欢

【LeetCode】4. Best Time to Buy and Sell Stock·股票买卖最佳时机

Analysis of the problems of the 11th Blue Bridge Cup single chip microcomputer provincial competition

Project experience sharing: realize an IR Fusion optimization pass of Shengsi mindspire layer

Dora (discover offer request recognition) process of obtaining IP address
![[mindspire paper presentation] summary of training skills in AAAI long tail problem](/img/34/9c9ec1b94edeecd4a3e7f20fdd8356.png)
[mindspire paper presentation] summary of training skills in AAAI long tail problem

PAT甲级 1028 List Sorting

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

Hnsw introduction and some reference articles in lucene9

c语言指针的概念

JS monitors empty objects and empty references
随机推荐
Some basic operations of reflection
技术干货|昇思MindSpore NLP模型迁移之Roberta ——情感分析任务
【MindSpore论文精讲】AAAI长尾问题中训练技巧的总结
Arduino Serial系列函数 有关print read 的总结
[set theory] order relation (partial order relation | partial order set | example of partial order set)
Map interface and method
Hnsw introduction and some reference articles in lucene9
图像识别与检测--笔记
Project experience sharing: realize an IR Fusion optimization pass of Shengsi mindspire layer
Vertx multi vertical shared data
項目經驗分享:實現一個昇思MindSpore 圖層 IR 融合優化 pass
Use of file class
项目经验分享:基于昇思MindSpore实现手写汉字识别
Introduction of buffer flow
Technical dry goods | reproduce iccv2021 best paper swing transformer with Shengsi mindspire
研究显示乳腺癌细胞更容易在患者睡觉时进入血液
Rabbit MQ message sending of vertx
【MySQL 11】怎么解决MySQL 8.0.18 大小写敏感问题
JUnit unit test of vertx
技术干货|昇思MindSpore算子并行+异构并行,使能32卡训练2420亿参数模型