'In Go, is there similar feature like "f-string" in Python? [duplicate]
In Go, is there a similar feature like "f-string" in Python? I cannot find a simple solution like f-string.
#Python
name = 'AlphaGo'
print(f'I am {name}') ##I am AlphaGo
A best alternative solution I found on the web and from comment is
//Golang
package main
import (
"fmt"
)
func main() {
const name, age = "Kim", 22
fmt.Println(name, "is", age, "years old.") // Kim is 22 years old.
}
But, this is still not as simple as f-string...
Solution 1:[1]
- Simply use:
fmt.Printf("I am %s\n", name) // I am AlphaGo
- Exported
Name
, usestruct
:
t := template.Must(template.New("my").Parse("I am {{.Name}}\n"))
t.Execute(os.Stdout, struct{ Name string }{name}) // I am AlphaGo
- Lower case
name
, usemap
:
t2 := template.Must(template.New("my").Parse("I am {{.name}}\n"))
t2.Execute(os.Stdout, map[string]string{"name": name}) // I am AlphaGo
- Use
.
:
t3 := template.Must(template.New("my").Parse("I am {{.}}\n"))
t3.Execute(os.Stdout, name) // I am AlphaGo
All - 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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |