如何在 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 的信息,您可以浏览这些教程。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP