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.
结论
以上是两个带参数和返回值的函数的例子。这些类型的函数的主要使用情况是,如果你想对参数进行一些操作并返回结果,那么我们可以创建一个带参数和返回值的函数。
极客教程