当前位置:网站首页>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)
}
边栏推荐
- With the development of industrial Internet, the landing and application of the Internet has become wider
- How to execute a query SQL
- Wuenda 2022 machine learning special course evaluation is coming!
- 一文讲清楚什么是类型化数组、ArrayBuffer、TypedArray、DataView等概念
- Unity 频繁切换分支 结果模型出现莫名其妙的错误
- 损失函数:DIOU loss手写实现
- A keepalived high availability accident made me learn it again!
- How can I protect my private key?
- golang模板(text/template)
- QQ was stolen? The reason is
猜你喜欢

提权扫描工具

可观测,才可靠:云上自动化运维CloudOps系列沙龙 第一弹
![【科研数据处理】[基础]类别变量频数分析图表、数值变量分布图表与正态性检验(包含对数正态)](/img/70/8bf226964118efb324ca4d339df654.png)
【科研数据处理】[基础]类别变量频数分析图表、数值变量分布图表与正态性检验(包含对数正态)

为基础性语言摇旗呐喊

Apache Doris Compaction优化百科全书

Observable, reliable: the first shot of cloudops series Salon of cloud automation operation and maintenance

【观察】智能产业加速,为何AI算力要先行?

IM即时通讯应用开发中无法解决的“顽疾”

SQL考勤统计月报表

Google Earth Engine(GEE)——GHSL:全球人类住区层,建成网格 1975-1990-2000-2015 (P2016) 数据集
随机推荐
navicat数据库建表是没有utf8选项。
Apache Doris Compaction优化百科全书
DNS 解析之家庭网络接入 Public DNS 实战
【Kubernetes系列】K8s设置MySQL8大小写不敏感
为基础性语言摇旗呐喊
The programming competition is coming! B station surrounding, senior members and other good gifts to you!
What is erdma as illustrated by Coptic cartoon?
Calculates the length of the last word in a string, separated by spaces
Lifting scanning tool
我如何才能保护我的私钥?
Google Earth Engine(GEE)——GHSL:全球人类住区层,建成网格 1975-1990-2000-2015 (P2016) 数据集
半导体动态杂谈
Why can't the database table be written into data
Embedded development: five C features that may no longer be prohibited
QQ was stolen? The reason is
Numpy creates an empty array data = np empty(shape=[1, 64,64,3])
golang模板(text/template)
Exlipse operates on multiple rows at the same time. For example, input the same text in multiple lines and columns at the same time
Read all the knowledge points about enterprise im in one article
SQL考勤统计月报表