2 回答

TA貢獻1780條經驗 獲得超5個贊
這是可能的,但必須修改格式字符串,您必須使用顯式參數索引:
顯式參數索引:
在 Printf、Sprintf 和 Fprintf 中,每個格式化動詞的默認行為是格式化調用中傳遞的連續參數。但是,動詞前的符號 [n] 表示要對第 n 個單索引參數進行格式化。寬度或精度的“*”之前的相同符號選擇保存該值的參數索引。在處理括號表達式 [n] 后,后續動詞將使用參數 n+1、n+2 等,除非另有說明。
你的例子:
val := "foo" s := fmt.Sprintf("%[1]v in %[1]v is %[1]v", val) fmt.Println(s)
輸出(在Go Playground上試試):
foo in foo is foo
當然上面的例子可以簡單的寫成一行:
fmt.Printf("%[1]v in %[1]v is %[1]v", "foo")
同樣作為一個小的簡化,第一個顯式參數索引可以省略,因為它默認為1
:
fmt.Printf("%v in %[1]v is %[1]v", "foo")

TA貢獻1793條經驗 獲得超6個贊
你也可以使用text/template:
package main
import (
"strings"
"text/template"
)
func format(s string, v interface{}) string {
t, b := new(template.Template), new(strings.Builder)
template.Must(t.Parse(s)).Execute(b, v)
return b.String()
}
func main() {
val := "foo"
s := format("{{.}} in {{.}} is {{.}}", val)
println(s)
}
https://pkg.go.dev/text/template
- 2 回答
- 0 關注
- 227 瀏覽
添加回答
舉報