有没有一种高效的方法来连接字符串?

huangapple go评论75阅读模式
英文:

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 }}

huangapple
  • 本文由 发表于 2017年7月29日 21:25:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/45389802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定