go语言中的函数(译)

135 阅读3分钟

这是我参与2022首次更文挑战的第15天,活动详情查看:2022首次更文挑战

原文链接:www.geeksforgeeks.org/functions-i…

函数通常是代码块或者在程序里面的语句,方便用户重用相同代码的能力,最终节省过多的使用内存,表现出来是节省时间并且更重要的是,提供代码更好的可读性。基本上,函数是一个可以运行一些特殊的任务并且给调用者返回结构的语句的集合。一个函数也可以运行特殊任务而不需要返回任何东西。

Function Declaration

函数声明意思是构造一个函数的方式

Syntax(语法)

func function_name(Parameter-list)(Return_type){
    // function body.....
}

函数声明包含:

  • func:go语言中的关键字,用来创建一个函数
  • function_name:函数名称
  • Parameter-list: 函数参数的名称和类型
  • Return_type 它是可选的,并且它包含返回值的类型。如果你在函数使用了返回类型,你的函数就必须使用一个return语句。

image.png

Function Calling

用户想执行函数时,函数掉用就完成了。函数功能需要被调用。就像下面的例子展示的那样,我们有一个叫做area()的函数,包含了两个参数。现在我们在main函数中使用名字调用这个函数。例如:area(12,10)带了两个参数。

例子:

// Go program to illustrate the
// use of function
package main
import "fmt"

// area() is used to find the
// area of the rectangle
// area() function two parameters,
// i.e, length and width
func area(length, width int)int{
	
	Ar := length* width
	return Ar
}

// Main function
func main() {
    // Display the area of the rectangle
    // with method calling
    fmt.Printf("Area of rectangle is : %d", area(12, 10))
}

输出

Area of rectangle is : 120

Function Arguments

在go语言中,传递给一个函数的参数被叫做实参,但是函数实际接收的参数叫做形参。
Note:默认情况下go语言函数中使用值方法传递参数调用。
go语言支持两种方式来传递参数到函数中。

  • Call by value(值调用):在这种参数传递方法中,实际参数的值被复制到函数的形参中,并且两种类型的参数被保存在不同的内存位置。所以在函数内部的任何改变,不会影响到调用者的实际参数。
    例子
// Go program to illustrate the
// concept of the call by value
package main

import "fmt"

// function which swap values
func swap(a, b int)int{

	var o int
	o= a
	a=b
	b=o
	
return o
}

// Main function
func main() {
    var p int = 10
    var q int = 20
    fmt.Printf("p = %d and q = %d", p, q)

    // call by values
    swap(p, q)
    fmt.Printf("\np = %d and q = %d",p, q)
}

输出

p = 10 and q = 20
p = 10 and q = 20
  • Call by reference:(引用调用) 实参和形参都指向相同的位置,所以函数内部的任何修改会实际影响到调用者的实际参数。 例子
// Go program to illustrate the
// concept of the call by reference
package main

import "fmt"

// function which swap values
func swap(a, b *int)int{
	var o int
	o = *a
	*a = *b
	*b = o
	
return o
}

// Main function
func main() {

    var p int = 10
    var q int = 20
    fmt.Printf("p = %d and q = %d", p, q)

    // call by reference
    swap(&p, &q)
    fmt.Printf("\np = %d and q = %d",p, q)
}

输出

p = 10 and q = 20
p = 20 and q = 10