使用Go語言建立包含常量的模組


在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!

結論

我們使用兩個示例執行並編譯了建立包含常量的模組的程式。在第一個示例中,我們建立了一個常量字串,然後返回並列印它。在第二個示例中,我們建立了一個用作常量的函式,字串返回給函式,並在主函式中列印到控制檯。

更新於:2023年7月19日

61 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告