Golang 创建带有常量的 Golang 模块的程序
在 Go 编程语言中,模块是包的集合,并且它有助于管理它们及其依赖关系。本文将使用两个示例创建一个带有常量的模块。在第一个示例中,我们将创建一个常量字符串,该字符串将由函数返回,并且该函数将从另一个模块的主函数中调用。在第二个示例中,将创建一个函数来返回字符串,并在另一个模块的主函数调用时打印字符串。
步骤
- 在程序中导入所需的包
-
在包中创建一个常量字符串
-
在另一个包中调用该包并打印常量字符串
-
使用 fmt 包中的 Println 函数执行打印语句
示例1
在此例中,我们将创建一个名为 mymodule 的包,该包将被导入到另一个模块中。我们将创建一个常量字符串,这意味着它不能被更改,然后将创建一个函数 sayHello,该函数将返回创建的常量字符串。当该包在主函数中被导入时,将调用该函数,并使用 fmt 包中的 Println 函数打印常量字符串。
//Golang program to create a module with constant
package mymodule
const Greetingalexa = "Hello, alexa!" //create string using const keyword
func SayHello() string {
return Greetingalexa //return the string to the function
}
package main
import (
"fmt"
"path/to/mymodule" //import the previous module in this module
)
//Main function to execute the program
func main() {
fmt.Println(mymodule.SayHello()) //call the function and print the statement
}
输出
Hello, alexa!
示例2
在这个示例中,程序将创建一个名为mymodule的包,并创建一个名为Greetingalexa的函数,在该函数中直接返回字符串给函数调用者。在这里,函数将作为常量使用,它将从另一个模块调用,并且使用fmt包的Println函数将输出打印到控制台上。
//Golang program to create a module with constant
package mymodule
func Greetingalexa() string { //create a function and return the string
return "Hello, alexa!"
}
package main
import (
"fmt"
"path/to/mymodule" //import the previous module in this module
)
//Main function to execute the program
func main() {
fmt.Println(mymodule.Greetingalexa()) //call the function and print the statement
}
输出
Hello,alexa!
结论
我们执行并编译了使用两个示例创建常量模块的程序。在第一个示例中,我们创建了一个常量字符串,然后返回并打印它。在第二个示例中,我们创建了一个作为常量的函数,字符串被返回给该函数,并在主函数中打印到控制台上。