英文:
Is there an efficient way to concatenate strings
问题
例如,有一个这样的函数:
func TestFunc(str string) string {
return strings.Trim(str," ")
}
它在下面的示例中运行:
{{ $var := printf "%s%s" "x" "y" }}
{{ TestFunc $var }}
有没有办法在模板中使用运算符连接字符串?
{{ $var := "y" }}
{{ TestFunc "x" + $var }}
或者
{{ $var := "y" }}
{{ TestFunc "x" + {$var} }}
它会给出意外的" + "在操作数错误中。
我在文档中找不到相关信息(https://golang.org/pkg/text/template/)
英文:
For example, there is a function like that:
func TestFunc(str string) string {
return strings.Trim(str," ")
}
It runs in the example below:
{{ $var := printf "%s%s" "x" "y" }}
{{ TestFunc $var }}
Is there anyway to concatenate strings with operators in template ?
{{ $var := "y" }}
{{ TestFunc "x" + $var }}
or
{{ $var := "y" }}
{{ TestFunc "x" + {$var} }}
It gives unexpected "+" in operand error.
I couldnt find it in documentation (https://golang.org/pkg/text/template/)
答案1
得分: 24
在Go模板中,没有使用运算符来连接字符串的方法。
可以使用printf
函数,如问题中所示,或将调用组合在一个单一的模板表达式中:
{{ TestFunc (printf "%s%s" "x" "y") }}
如果你总是需要为TestFunc参数连接字符串,那么可以编写TestFunc来处理连接操作:
func TestFunc(strs ...string) string {
return strings.Trim(strings.Join(strs, ""), " ")
}
{{ TestFunc "x" $var }}
英文:
There is not a way to concatenate strings with an operator because Go templates do not have operators.
Use the printf
function as shown in the question or combine the calls in a single template expression:
{{ TestFunc (printf "%s%s" "x" "y") }}
If you always need to concatenate strings for the TestFunc argument, then write TestFunc to handle the concatenation:
func TestFunc(strs ...string) string {
return strings.Trim(strings.Join(strs, ""), " ")
}
{{ TestFunc "x" $var }}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论