Golang 如何创建一个没有参数但有返回值的函数
这个教程将教我们如何创建一个没有参数但有返回值的函数。这个教程涉及到有关函数的要点,以及在Golang中创建没有参数但有返回类型的函数的语法,最后我们将看到两个不同的实例,这两个实例分别创建了没有参数但有返回类型的函数。在这两个示例中,无论何时调用,我们都将返回一个字符串。
没有参数但有返回类型的函数。
语法
现在我们将看到没有参数但有返回类型的函数的语法和解释。
func functionName( ) (returnType1, returnType2, …) {
return returnValue1, returnValue2, …
}
解释
- func是Golang中告诉编译器函数被定义了的关键词。
-
函数的名字必须以字母开头,紧接着是函数关键词。
-
由于不需要参数,我们在函数名后面写上空括号()。
-
为了声明返回类型,我们将它们写在参数声明之后的单独的括号中。
-
在花括号之间,我们可以写出函数的逻辑。
-
在整个逻辑写完之后,我们使用return关键词返回我们想要返回的所有值。
步骤
-
步骤 1 − 开始main()函数。
-
步骤 2 − 调用没有参数但有返回值的函数,并将返回的值存储在相应的变量中。
-
步骤 3 − 声明函数,在函数体中写逻辑,并在最后返回值。
-
步骤 4 − 对函数返回的值进行必要的操作。
示例1
在这个示例中,我们创建了两个函数FirstSmall()和SecondSmall(),分别返回一个字符串,根据第一个数和第二个数的大小进行调用。
package main
import (
// fmt package provides the function to print anything
"fmt"
)
func FirstSmall() string {
return "First number is smaller than the second."
}
func SecondSmall() string {
return "Second number is smaller than the first."
}
func main() {
// declaring the variables
var firstNumber, secondNumber int
// initializing the variable
firstNumber = 10
secondNumber = 8
fmt.Println("Golang program to learn how to create a function without argument but with return value.")
fmt.Println("Comparing the numbers and printing the message by calling a function.")
if firstNumber < secondNumber {
fmt.Println(FirstSmall())
} else {
fmt.Println(SecondSmall())
}
}
输出
Golang program to learn how to create a function without argument but with return value.
Comparing the numbers and printing the message by calling a function.
Second number is smaller than the first.
示例2
在此示例中,我们创建了两个函数 evenNumber() 和 oddNumber(),分别返回一个字符串,如果数字是偶数,则调用偶数的字符串,如果数字是奇数,则调用奇数的字符串。
package main
import (
// fmt package provides the function to print anything
"fmt"
)
func evenNumber() string {
return "Number is even."
}
func oddNumber() string {
return "Number is odd."
}
func main() {
// declaring and initializing the array
numberArray := [5]int{32, 45, 67, 3, 88}
fmt.Println("Golang program to learn how to create a function without argument but with return value.")
fmt.Println("Checking the array element is odd or even.")
// running for loop on the array
for i := 0; i < 5; i++ {
// checking the number at index i is odd or even
if numberArray[i]%2 == 0 {
fmt.Println(numberArray[i], evenNumber())
} else {
fmt.Println(numberArray[i], oddNumber())
}
}
}
输出
Golang program to learn how to create a function without argument but with return value.
Checking the array element is odd or even.
32 Number is even.
45 Number is odd.
67 Number is odd.
3 Number is odd.
88 Number is even.
结论
这是两个没有参数但有返回值的函数的示例。这种类型的函数的主要使用场景是,如果您想要多次执行同一类型的操作并返回相同的值,那么我们可以创建一个没有参数但有返回值的函数。要了解更多关于Golang的内容,您可以浏览这些教程。