首页 > 解决方案 > 使用变量注入字符串模板

问题描述

我在看这篇文章:

https://medium.com/@IndianGuru/understanding-go-s-template-package-c5307758fab0

我想知道如何使用模板将变量注入字符串,例如:

func getTemplate(v string) string {
    return `CREATE TABLE share_${v} PARTITION OF share FOR VALUES IN (${v});`
}

文章中的示例将输出写入标准输出,但我需要将模板的结果存储为变量,有人知道怎么做吗?

就像是:

result := getTemplate("0")

标签: go

解决方案


Golang 模板是他妈的疯子。这应该有效:

func getTableCreationCommands(v string) string {
    return `
      CREATE TABLE share_` + v + ` PARTITION OF share FOR VALUES IN (` + v + `);
      CREATE TABLE nearby_` + v + ` PARTITION OF nearby FOR VALUES IN (` + v + `);
    `
}

推荐阅读