Go语言中的函数用法指南

2021年4月3日18:50:41 发表评论 638 次浏览

本文概述

函数通常是程序中的代码或语句块, 使用户能够重用相同的代码, 从而最终节省了过多的内存使用, 节省了时间, 更重要的是, 提供了更好的代码可读性。因此, 基本上, 函数是语句的集合, 这些语句执行某些特定的任务并将结果返回给调用方。函数也可以执行某些特定任务而无需返回任何内容。

函数声明

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

语法如下:

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

该函数的声明包含:

  • 函数:它是Go语言的关键字, 用于创建函数。
  • function_name:它是函数的名称。
  • 参数列表:它包含函数参数的名称和类型。
  • Return_type:它是可选的, 并且包含函数返回的值的类型。如果在函数中使用return_type, 则必须在函数中使用return语句。
Go语言中的函数1

函数调用

当用户想要执行函数时, 完成函数调用或函数调用。使用该函数需要调用该函数。如下例所示, 我们有一个名为area()的函数, 带有两个参数。现在我们通过使用其名称, 即具有两个参数的area(12, 10)在主函数中调用此函数。

例子:

C

// 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语言支持两种向函数传递参数的方法:

  • 按值致电::在这种参数传递方法中, 实际参数的值被复制到函数的形式参数中, 并且两种类型的参数存储在不同的存储位置中。因此, 在函数内部进行的任何更改都不会反映在调用者的实际参数中。
    例子:
     

C

// 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
  • 致电查询:实际参数和形式参数都指向相同的位置, 因此在函数内部所做的任何更改实际上都会反映在调用者的实际参数中。
    例子:
     

C

// 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

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: