Golang 函数

Golang 函数

函数通常是程序中的代码块或语句,它使用户能够重复使用相同的代码,最终节省了过多的内存使用,起到了节省时间的作用,更重要的是,提供了更好的代码可读性。因此,基本上,一个函数是一个语句的集合,执行一些特定的任务,并将结果返回给调用者。一个函数也可以执行一些特定的任务而不返回任何东西。

函数声明

函数声明是指构造一个函数的方法。

语法:

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

该函数的声明包含:

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

Go语言中的函数

函数调用

当用户想执行函数时,就会进行函数调用。为了使用其功能,需要调用该函数。如下面的例子所示,我们有一个名为 area() 的函数,有两个参数。现在我们在主函数中通过使用其名称来调用这个函数,即带两个参数的 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

函数参数

在Go语言中,传递给函数的参数被称为实际参数,而函数接收的参数被称为形式参数。
注意: 默认情况下,Go语言使用按值调用的方法在函数中传递参数。
Go语言支持两种方式向函数传递参数:

  • 按值调用: :在这种参数传递方式中,实际参数的值被复制到函数的形式参数中,两种类型的参数被存储在不同的内存位置。所以在函数内部的任何改变都不会反映在调用者的实际参数中。
    例子:
// 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

  • 引用调用: 实际参数和形式参数都指向相同的位置,因此在函数内部的任何变化实际上都反映在调用者的实际参数中。
    例子:
// 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程