Golang 如何创建一个带有参数但没有返回值的函数
本教程将教我们如何创建一个带有参数但没有返回值的函数。本教程介绍了函数的要点,以及Golang中带有参数且没有返回类型的函数的语法,最后我们将看到两个不同的带有参数但没有返回类型的函数的示例。在第一个示例中,我们将打印传递给函数的参数及其对应的语句。在另一个示例中,我们将添加作为参数传递的数字,并在同一个函数中打印出它们的和。
带有参数但没有返回类型的函数。
语法
现在,我们将看到带有参数但没有返回类型的函数的语法和解释。
func functionName(argumentName1 argumentType, argumentName2 argumentType, …) {
}
说明
- func是Golang中声明函数的关键字。
-
紧接着函数关键字后面,我们写上以字母开头的函数名。
-
现在我们将参数写在圆括号()内,参数名在前,参数类型在后。
-
由于我们不需要返回值,所以在圆括号和花括号之间不需要写任何内容。
-
花括号之间我们可以写函数的逻辑。
步骤
-
步骤1 - 定义要传递给函数的变量。
-
步骤2 - 初始化变量。
-
步骤3 - 使用相应的参数调用函数。
-
步骤4 - 声明函数并在函数体中编写逻辑。
示例1
在这个示例中,我们传入一个参数,该参数表示芒果的数量,并在函数中打印这些芒果,不返回任何值。
package main
import (
// fmt package provides the function to print anything
"fmt"
)
// declare the function with argument and without return value
func PrintTotalMangoes(numberOfMangoes int) {
fmt.Println("The total number of mangoes is ", numberOfMangoes)
}
func main() {
// declaring the variable
var numberOfMangoes int
// initializing the variable
numberOfMangoes = 10
fmt.Println("Golang program to learn how to create a function with an argument but no return value.")
fmt.Println("Print the total number of mangoes.")
// calling the function with arguments
PrintTotalMangoes(numberOfMangoes)
}
输出
Golang program to learn how to create a function with an argument but no return value.
Print the total number of mangoes.
The total number of mangoes is 10
示例2
在这个示例中,我们将两个参数传递给函数,这两个参数的值是我们要打印出来的两个数字的和。这个函数带有一个参数,并且没有返回值。
package main
import (
// fmt package provides the function to print anything
"fmt"
)
// declare the function with argument and without return value
func Addition(number1, number2 int) {
// declaring the variable
var number3 int
// adding value of two variables and storing in the third variable
number3 = number1 + number2
fmt.Printf("The addition of %d and %d is %d.\n", number1, number2, number3)
}
func main() {
// declaring the variables
var number1, number2 int
// initializing the variable
number1 = 10
number2 = 8
fmt.Println("Golang program to learn how to create a function with an argument but no return value.")
fmt.Println("Print the addition of two numbers.")
// calling the function with arguments
Addition(number1, number2)
}
输出
Golang program to learn how to create a function with an argument but no return value.
Print the addition of two numbers.
The addition of 10 and 8 is 18.
结论
这是两个具有参数但没有返回值的函数的示例。这种类型的函数的主要用例是,如果您想在函数中对变量执行某些操作,并希望在同一个函数中打印,则具有参数但没有返回值的函数是正确的选择。要了解更多关于Golang的信息,您可以浏览这些教程。
极客笔记