在 Go 中,是否有类似 Python 中的“f-string”的功能? [复制]

分享于2022年07月17日 go 问答
【问题标题】:在 Go 中,是否有类似 Python 中的“f-string”的功能? [复制](In Go, is there similar feature like "f-string" in Python? [duplicate])
【发布时间】:2022-04-28 19:18:17
【问题描述】:

在围棋中, Python中是否有类似“f-string”的功能? 我找不到像 f-string 这样的简单解决方案。

#Python
name = 'AlphaGo'
print(f'I am {name}') ##I am AlphaGo

我在网上和评论中找到的最佳替代解决方案是

//Golang
package main

import (
    "fmt"
)

func main() {
    const name, age = "Kim", 22
    fmt.Println(name, "is", age, "years old.") // Kim is 22 years old.
}

但是,这还是没有f-string那么简单……


【解决方案1】:
  1. 简单使用:
fmt.Printf("I am %s\n", name) // I am AlphaGo

  1. 导出 Name ,使用 struct
    t := template.Must(template.New("my").Parse("I am {{.Name}}\n"))
    t.Execute(os.Stdout, struct{ Name string }{name}) // I am AlphaGo

  1. 小写 name ,使用 map
    t2 := template.Must(template.New("my").Parse("I am {{.name}}\n"))
    t2.Execute(os.Stdout, map[string]string{"name": name}) // I am AlphaGo

  1. 使用 . :
    t3 := template.Must(template.New("my").Parse("I am {{.}}\n"))
    t3.Execute(os.Stdout, name) // I am AlphaGo

全部 - try it on The Go Playground :

package main

import (
    "fmt"
    "os"
    "text/template"
)

func main() {
    name := "AlphaGo"

    fmt.Printf("I am %s\n", name)

    t := template.Must(template.New("my").Parse("I am {{.Name}}\n"))
    t.Execute(os.Stdout, struct{ Name string }{name}) // I am AlphaGo

    t2 := template.Must(template.New("my").Parse("I am {{.name}}\n"))
    t2.Execute(os.Stdout, map[string]string{"name": name}) // I am AlphaGo

    t3 := template.Must(template.New("my").Parse("I am {{.}}\n"))
    t3.Execute(os.Stdout, name) // I am AlphaGo
}