Golang中如何实现多行字符串插值

Golang中如何实现多行字符串插值 大家好,我目前还没有找到关于这个问题的示例:

是否可能返回一个插入了变量实际值的字符串?

假设我们有一个多行字符串,如下所示:

placeHoldersString := `Your name: %s \n
    Your city: %s
    Your country: %s`

我是否可以使用 filledString := fmt.Sprintf(placeHoldersString, name, city, country) 来返回

Your name: John Doe
Your city: New Jersey
Your country: USA

或者类似的效果……,还是我应该采用其他方法?


更多关于Golang中如何实现多行字符串插值的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

juniormayhe:

我可以使用 filledString := fmt.Sprintf(placeHoldersString, name, city, country) 吗?

是的:Go Playground - The Go Programming Language

juniormayhe:

还是我应该采用另一种方法?

我们需要更多上下文信息才能判断你是否应该采用另一种方法!

更多关于Golang中如何实现多行字符串插值的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中,你可以使用fmt.Sprintf来实现多行字符串插值,但需要注意原始字符串字面量(反引号)中的转义字符不会被解析。对于你的例子,应该使用双引号字符串或者调整格式。以下是几种实现方式:

方法1:使用双引号字符串(推荐)

package main

import "fmt"

func main() {
    name, city, country := "John Doe", "New Jersey", "USA"
    
    // 使用双引号字符串,\n会被解析为换行
    placeHoldersString := "Your name: %s\nYour city: %s\nYour country: %s"
    
    filledString := fmt.Sprintf(placeHoldersString, name, city, country)
    fmt.Print(filledString)
}

方法2:使用反引号并显式添加换行

package main

import "fmt"

func main() {
    name, city, country := "John Doe", "New Jersey", "USA"
    
    // 反引号字符串中直接换行
    placeHoldersString := `Your name: %s
Your city: %s
Your country: %s`
    
    filledString := fmt.Sprintf(placeHoldersString, name, city, country)
    fmt.Print(filledString)
}

方法3:使用strings.Join构建

package main

import (
    "fmt"
    "strings"
)

func main() {
    name, city, country := "John Doe", "New Jersey", "USA"
    
    lines := []string{
        fmt.Sprintf("Your name: %s", name),
        fmt.Sprintf("Your city: %s", city),
        fmt.Sprintf("Your country: %s", country),
    }
    
    filledString := strings.Join(lines, "\n")
    fmt.Print(filledString)
}

方法4:使用text/template(适合复杂场景)

package main

import (
    "bytes"
    "text/template"
)

func main() {
    name, city, country := "John Doe", "New Jersey", "USA"
    
    tmpl := `Your name: {{.Name}}
Your city: {{.City}}
Your country: {{.Country}}`
    
    t, _ := template.New("test").Parse(tmpl)
    
    data := struct {
        Name    string
        City    string
        Country string
    }{
        Name:    name,
        City:    city,
        Country: country,
    }
    
    var buf bytes.Buffer
    t.Execute(&buf, data)
    filledString := buf.String()
    print(filledString)
}

你的原始代码中\n在反引号中不会被解析为换行符,所以输出会是字面的\n。以上方法都能正确输出:

Your name: John Doe
Your city: New Jersey
Your country: USA

根据你的具体需求选择合适的方法,简单插值推荐使用方法1或2,复杂模板推荐使用方法4。

回到顶部