Golang 如何创建带参数和返回值的函数
本教程将教我们如何创建带有参数和返回值的函数。本教程介绍了有关函数的要点,以及在Golang中使用参数和返回类型定义函数的语法,然后我们将看到两个不同的示例,一个是带参数和返回值的函数,另一个是计算圆的面积。
编程语言中的函数。
让我们首先了解什么是函数。函数是程序的一个子集,使代码具有模块化的特性。函数使得特定的代码可以被重用。函数在调用时支持参数,并且根据我们的需求可以有返回类型。
带参数和返回值的函数
语法
现在我们将看到带有参数和返回类型的函数的语法和解释。
func functionName(argumentName1 argumentType, argumentName2 argumentType, …) (returnType1, returnType2, …) {
return returnValue1, returnValue2, …
}
解释
- func是Golang中告诉编译器函数被定义的关键字。
-
紧接着函数名写在函数旁边,函数名必须以字母开头。
-
现在我们将参数写在圆括号()之间,参数名在前,后面跟上数据类型。
-
在声明参数之后,我们用另一对圆括号()来写返回类型。
-
在花括号{}之间,我们可以写函数的逻辑。
-
当整个逻辑被写完后,我们将使用return关键字来返回我们想要返回的所有值。
步骤
-
步骤1 - 开始main()函数。
-
步骤2 - 用参数和返回值调用函数,并将值存储在相应的变量中。
-
步骤3 - 声明函数,在函数体中编写逻辑,并在最后返回值。
-
步骤4 - 对函数返回的值执行所需操作。
示例1
在这个示例中,我们将创建一个函数来求两个数的和,其中我们将数字作为参数传递并返回和值。
package main
import (
// fmt package provides the function to print anything
"fmt"
)
// declaring a function with argument and with return value
func sumOfTwoNumbers(number1, number2 int) int {
// returning the sum
return number1 + number2
}
func main() {
// declaring the variables
var number1, number2, sumOfNumbers int
// initializing the variables
number1 = 21
number2 = 32
fmt.Println("Golang program to learn how to create a function with argument and with the return value.")
fmt.Println("Finding sum of two numbers.")
// calling the function by passing both the numbers as an argument and storing the value return by function in a variable
sumOfNumbers = sumOfTwoNumbers(number1, number2)
// printing the result
fmt.Printf("The sum of %d and %d is %d. \n", number1, number2, sumOfNumbers)
}
输出
Golang program to learn how to create a function with argument and with the return value.
Finding the sum of two numbers.
The Sum of 21 and 32 is 53.
示例2
在这个示例中,我们将创建一个函数来找到圆的面积,我们将半径作为参数传递并返回面积。
package main
import (
// fmt package provides the function to print anything
"fmt"
)
// declaring function with argument and with return value
func AreaOfCircle(radius float32) float32 {
// returning the area of the circle
return (22 / 7.0) * radius * radius
}
func main() {
// declaring the variable
var radius, areaOfCircle float32
// initializing the variable
radius = 3.5
fmt.Println("Golang program to learn how to create a function with argument and with the return value.")
fmt.Println("Finding the area of the circle.")
// calling the function by passing radius as argument and storing the value area return by function in a variable
areaOfCircle = AreaOfCircle(radius)
// printing the result
fmt.Printf("The area of the circle with radius %f cm is %f cm^2. \n", radius, areaOfCircle)
}
输出
Golang program to learn how to create a function with argument and with return value.
Finding the area of the circle.
The area of the circle with radius 3.500000 cm is 38.500000 cm^2.
结论
这是两个带有参数和返回值的函数的示例。这些类型的函数的主要用途是,如果您想对参数执行某些操作并返回结果,那么可以创建一个带有参数且具有返回值的函数。要了解更多关于Golang的信息,您可以查阅这些教程。