當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang os.Expand()用法及代碼示例

問題解決方法:

在這個程序中,我們將使用 os.Expand() 函數用指定的函數擴展或格式化指定的字符串,並將結果打印在控製台屏幕上。

程序/源代碼:

下麵給出了演示 os.Expand() 函數的源代碼。給定的程序在 ubuntu 18.04 操作係統上編譯和執行成功。

// Golang program to demonstrate the
// os.Expand() function

package main

import "fmt"
import "os"

func GetVal(val string) string {
	switch val {
	case "Name":
		return "Morrish"
	case "City":
		return "New York"
	default:
		return "<Empty>"
	}
}

func main() {
	str:= "My name is $Name and live in $City."

	//Format the specified string using os.Expand
	strResult:= os.Expand(str, GetVal)

	fmt.Println(strResult)
}

輸出:

My name is Morrish and live in New York.

說明:

在上麵的程序中,我們聲明了包 main。 main 包用於告訴 Go 語言編譯器必須編譯該包並生成可執行文件。在這裏,我們導入了 "fmt" 包以使用 Printf() 函數,我們還導入了 "os" 包以使用 Expand() 函數。

func GetVal(val string) string {
	switch val {
	case "Name":
		return "Morrish"
	case "City":
		return "New York"
	default:
		return "<Empty>"
	}
}

在上麵的代碼中,我們創建了一個函數 GetVal(),它根據指定的參數返回值。

在 main() 函數中,我們使用 os.Expand() 函數格式化一個字符串並在控製台屏幕上打印結果。





相關用法


注:本文由純淨天空篩選整理自 Golang program to demonstrate the os.Expand() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。