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