当前位置:网站首页>Go language func function
Go language func function
2022-06-30 14:09:00 【Zhen Jie.】
One 、 Function definition
Functions are the smallest modular units in structured programming , In the course of daily development , The complex algorithm process is decomposed into several small tasks ( Code block ), Make the structure of the program clearer , Program readability is improved , Easy to maintain and let others understand your code .
The main purpose of writing multiple functions is to decompose a complex problem that requires many lines of code into a series of simple tasks ( That's the function ) To solve . In actual programming , We abstract the repetitive task into a function .
Like all programming languages ,Go The language supports various styles of functions . stay Go In language , When the function executes to the last line of the code block } Before or return Statement will exit , among return Statements can take zero or more parameters ; These parameters are used by the caller as return values . ordinary return Statements can also be used to end for Dead cycle , Or end a Go coroutines (goroutine).
Two 、 Definition grammar
func Function name ( parameter list ) ( Return value list ) {
// The body of the function
}
func funcName (input1 type1, input2 type2) (output1 type1, output2 type2) {
// Logic code
// Return multiple values
return value1, value2
}
From the code above, we can see that :
1) keyword func To declare a function funcName;
2) A function can have one or more parameters , Each parameter is followed by a type , Between multiple parameters “,” Division ;
3) Function can return multiple values ;
4) The return value above declares two variables output1 and output2, If you don't want to make a statement, you can , Just two types ;
5) If there is only one return value and the return value variable is not declared , Then you can omit , Parentheses including return values ;
6) If there is no return value , Then omit the last return information directly ;
7) If there is a return value , Then you have to add... To the outer layer of the function return sentence ;
What needs to be emphasized here is ,Go The return value type of a language function is the same as the data type of a variable definition , We have to follow Go Linguistic “ Postposition principle ” Put it in the back , This and C Language function definitions are significantly different .
in addition ,Go In the language function definition, if the types of several adjacent parameters in the parameter list are the same , You can omit the previous variable type declaration from the parameter list .
func Add(a, b int) int {
// here a and b All are int type
// The body of the function
}
Last ,Go The position of the left curly bracket in the language function definition is mandatory , If the left curly bracket is not placed properly ,golang The compiler will report compilation errors . error !!! The left parenthesis must immediately follow the parenthesis
// error !!! The left parenthesis must immediately follow the parenthesis
func hello()
{
// The left parenthesis cannot start with another line !!!!
}
3、 ... and 、 Comprehensive sample code 1
// return a、b The maximum
func max(a, b int) int {
if a > b {
return a
}
return b
}
func main() {
x := 3
y := 4
z := 5
max_xy := max(x, y) // Call function max(x, y)
max_xz := max(x, z) // Call function max(x, z)
fmt.Printf("max(%d, %d) = %d\n", y, z, max(y, z)) // You can also call directly here
}
In the above one, we can see max Function has two arguments , They are all of the type int, Then the type of the first variable can be omitted ( namely a,b int, Instead of a int, b int), The default is the nearest type , The same goes for more than 2 Variables or return values of the same type . At the same time, we notice that its return value is a type , This is the ellipsis .
Four 、 Support multiple return values 、 Support named return value
Go Language functions can return more than one result , Namely support **“ Multiple value return ”**.
Go Language function multivalued return is generally used to handle errors . For example IO In operation , You may not succeed every time : The file may not exist or the disk may be damaged and the file cannot be read . Therefore, an additional result is usually returned as the error value when a function call has an error , It is customary to return the error value as the last result .
func sumProductDiff(i, j int) (int, int, int) {
// Multiple return values
return i+j, i*j, i-j
}
func Split(sum int) (x, y int) {
// Named return
x = sum * 4 / 9
y = sum - x
return
}
If it is Name the return value , You do not need to bring the variable name when returning , Because it is initialized directly in the function .
If the method is publicly accessible , It is recommended that you name the return value , Because the return value is unnamed , Although it makes the code more concise , But it will cause poor readability of the generated documents .
5、 ... and 、 Uncertain parameters
Go Function supports arguments . Functions that accept arguments have an indefinite number of arguments . To do that , First, you need to define a function to accept arguments :
func myfunc (arg ...int) {
}
arg …int tell Go This function takes an indefinite number of arguments . Be careful , The types of these parameters are all int.
Any number of parameters of this type can be passed when calling this function . In the body of a function , Variable arg It's a int Of slice.
for _, n := range arg {
fmt.Printf("And the number is: %d\n", n)
}
6、 ... and 、 Comprehensive sample code 2
Let's write three functions here , Show the most normal shape of the function in turn , Multivalued return and indefinite parameters .
func Add(i int, j int) (int) {
// Regular functions
return i+j
}
func Add_Multi_Sub(i, j int) (int, int, int) {
// Multiple value return
return i+j, i*j, i-j
}
func sum(nums ...int) {
// Argument function
total := 0
for _, num := range nums {
total += num
}
fmt.Println(total)
}
func main(){
a, b := 2,3
arr := []int{
1, 2, 3}
var c int = Add(a,b)
d,e,f := Add_Multi_Sub(a,b)
fmt.Println(c,d,e,f) // 5 5 6 -1
sum(arr...) // Pay attention to the form of parameter transmission 6
}
7、 ... and 、 Pass value and pass pointer
When we pass a parameter value to the called function , In fact, it's a share of this value copy, When modifying the parameter value in the called function , The corresponding arguments in the call function do not change , Because numerical changes only affect copy On .
// A simple function , The function is implemented +1 The operation of
func add1(a int) int {
a = a + 1 // Changed the a value
return a // Returns the new value
}
func main () {
x := 3
fmt.Println("x=", x) // Output "x=3"
x1 := add1(x)
fmt.Println("x+1=", x1) // Output "x+1=4"
fmt.Println("x=", x) // Output "x=3"
}
Although we call add1 function , And in add1 In the implementation of a = a+1 operation , But in the example above x The value of the variable does not change .
The reason is simple : Because when we call add1 When ,add1 The received parameters are actually x Of copy, instead of x In itself .
If you really need to send this x In itself , What to do ?
We know , Variables are stored at a certain address in memory , Modifying a variable is actually modifying the memory at the address of the variable . Only add1 The function knows x The address of the variable , To modify the x The value of the variable . So we need to put x Address &x Passing in functions , And the type of the parameter of the function is changed from int Change it to *int, That is, change to pointer type , To modify... In a function x The value of the variable . At this time, the parameter is still press copy Delivered , It's just copy It's a pointer .
// A simple function , The function is implemented +1 The operation of
func add1(a *int) int {
*a = *a + 1 // Changed the a value
return *a // Returns the new value
}
func main () {
x := 3
fmt.Println("x=", x) // Output "x=3"
x1 := add1(&x)
fmt.Println("x+1=", x1) // Output "x+1=4"
fmt.Println("x=", x) // Output "x=4"
}
such , We have reached the modification x Purpose .
So what are the benefits of passing pointers ?
1) Passing pointers enables multiple functions to operate on the same object ;
2) The pointer is lighter (8bytes), Just send the memory address , We can use the pointer to transfer large structures . If the parameter value is passed , In every time copy It will cost more system overhead ( Memory and time ). So when you want to transfer large structures , Using a pointer is a wise choice .
3)Go In language channel,slice,map These three types of implementation mechanisms are similar to pointers , So it can be delivered directly , Instead of taking the address and passing the pointer .( notes : If the function needs to change slice The length of , You still need to take the address delivery pointer )
8、 ... and 、 Function as value 、 type
stay Go The middle function is also a variable , We can go through type To define it , Its type is that all have the same parameters , A type of the same return value .
type typeName func(input1 inputType1, input2 inputType2 [, …]) (result1 resultType1 [, …])
What are the benefits of functions as types ? That is, you can pass this type of function as a value .
type testInt func(int) bool // Declared a function type
func isOdd(integer int) bool {
if integer%2 == 0 {
return false
}
return true
}
func isEven(integer int) bool {
if integer%2 == 0 {
return true
}
return false
}
// Declared function type as a parameter
func filter(slice []int, f testInt) []int {
var result []int
for _, value := range slice {
if f(value) {
result = append(result, value)
}
return result
}
func main() {
slice := []int {
1,2,3,4,5,6,7}
fmt.Println("slice=", slice)
odd := filter(slice, isOdd) // Functions are passed as values
fmt.Println("odd elements of slice are:", odd)
even := filter(slice, isEven) // Functions are passed as values
fmt.Println("even elements of slice are:", even)
}
Functions as values and types are very useful when we write some generic interfaces , We can see from the above example that testInt This type is a function type , Then two filter The parameters and return values of the function are the same as testInt The type is the same , But we can implement many kinds of logic , This makes our program very flexible .
Nine 、 Function can only judge whether it is nil
What is? nil?
Everyone knows , When you declare a variable But there is no wood optimal assignment ,golang Will automatically give your variable type a corresponding default zero value . This is the zero value for each type :
bool -> false
numbers -> 0
string -> ""
pointers -> nil
slices -> nil
maps -> nil
channels -> nil
functions -> nil
interfaces -> nil
func add(a, b int) int {
return a + b
}
func main() {
fmt.Println(add == nil)
//fmt.Println(add == 1) // error mismatched types func(int, int) int and int)
}
边栏推荐
- Google Earth Engine(GEE)——将字符串的转化为数字并且应用于时间搜索( ee.Date.fromYMD)
- More than 20 years after Hong Kong's return, Tupu digital twin Hong Kong Zhuhai Macao Bridge has shocked
- 数字化转型道阻且长,如何迈好关键的第一步
- [kubernetes series] k8s set mysql8 case insensitive
- 步骤详解 | 助您轻松提交 Google Play 数据安全表单
- Google Earth Engine(GEE)——GHSL:全球人类住区层,建成网格 1975-1990-2000-2015 (P2016) 数据集
- golang模板(text/template)
- 为基础性语言摇旗呐喊
- Dart 扩展特性
- Wuenda 2022 machine learning special course evaluation is coming!
猜你喜欢

mysql拒绝访问、管理员身份打开的

Wuenda 2022 machine learning special course evaluation is coming!

Basic syntax of unity script (1) - common operations of game objects

Step by step | help you easily submit Google play data security form

How to execute a query SQL

Configuration of headquarters dual computer hot standby and branch infrastructure for firewall Foundation

What is erdma as illustrated by Coptic cartoon?

SQL programming problem, test case failed

"Persistent diseases" that cannot be solved in IM application development
![[Title brushing] coco, who likes bananas](/img/66/5646ac7e644025ccaee7c17f62ce17.png)
[Title brushing] coco, who likes bananas
随机推荐
我如何才能保护我的私钥?
随着产业互联网的发展,有关互联网的落地和应用也就变得宽阔了起来
SQL考勤统计月报表
Details of gets, fgetc, fgets, Getc, getchar, putc, fputc, putchar, puts, fputs functions
目录相关命令
Jetpack compose for perfect screen fit
优思学院:六西格玛不只是统计!
Jetpack Compose 实现完美屏幕适配
There is no utf8 option for creating tables in Navicat database.
IM即时通讯应用开发中无法解决的“顽疾”
知识传播不能取代专业学习!
On the simplification and acceleration of join operation
半导体动态杂谈
Small exercise of process and signal
Complete TCP forwarding server (kernel linked list + mutex)
Dart 扩展特性
提权扫描工具
Deep understanding Net (2) kernel mode 3 Kernel mode construct mutex
数据库表为什么写不进数据了
表格储存中sql查询的时候,查询结果增加主键报错,查询结果超过10w行。需要对主键增加上多元索引吗?