Is there an efficient way to concatenate strings

♀尐吖头ヾ 提交于 2021-02-05 20:10:37

问题


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:


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


来源:https://stackoverflow.com/questions/45389802/is-there-an-efficient-way-to-concatenate-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!