1.简单的string
fmt.Sprintf()fmt.Sprint()fmt.Sprintln()SSxxx()string
例如:
s := fmt.Sprintf("Hi, my name is %s and I'm %d years old.", "Bob", 23)
s
Hi, my name is Bob and I'm 23 years old.
Sprintf()Sprint()
i := 23 s := fmt.Sprint("[age:", i, "]") // s will be "[age:23]"
stringstrings.Join()string
在Go游乐场试试这些。
2.复杂的string(文档)
fmt.Sprintf()
text/templatehtml/templatehtml/templatetext/templatetext/template
templatestring
structmap
例:
例如,假设您想要生成如下所示的电子邮件:
Hi [name]! Your account is ready, your user name is: [user-name] You have the following roles assigned: [role#1], [role#2], ... [role#n]
要生成这样的电子邮件消息体,可以使用下面的静态模板:
const emailTmpl = `Hi {{.Name}}! Your account is ready, your user name is: {{.UserName}} You have the following roles assigned: {{range $i, $r := .Roles}}{{if ne $i 0}}, {{end}}{{.}}{{end}} `
并提供这样的数据来执行它:
data := map[string]interface{}{ "Name": "Bob", "UserName": "bob92", "Roles": []string{"dbteam", "uiteam", "tester"}, }
io.Writerstringbytes.Bufferio.Writerstring
t := template.Must(template.New("email").Parse(emailTmpl)) buf := &bytes.Buffer{} if err := t.Execute(buf, data); err != nil { panic(err) } s := buf.String()
这将导致预期产出:
Hi Bob! Your account is ready, your user name is: bob92 You have the following roles assigned: dbteam, uiteam, tester
在Go Playground上试试吧。
os.Stdoutio.Writer
t := template.Must(template.New("email").Parse(emailTmpl)) if err := t.Execute(os.Stdout, data); err != nil { panic(err) }
os.Stdout