是否有连接字符串的有效方法 [英] Is there an efficient way to concatenate strings

查看:46
本文介绍了是否有连接字符串的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,有一个类似的功能:

For example, there is a function like that:

 func TestFunc(str string) string {
 return strings.Trim(str," ")
 }

它在以下示例中运行:

 {{ $var := printf "%s%s" "x" "y" }}
 {{ TestFunc $var }}

反正是在模板中用运算符将​​字符串连接起来吗?

Is there anyway to concatenate strings with operators in template ?

 {{ $var := "y" }}
 {{ TestFunc "x" + $var }}

 {{ $var := "y" }}
 {{ TestFunc "x" + {$var} }}

它在操作数错误中给出了意外的"+".

It gives unexpected "+" in operand error.

我在文档中找不到它( https://golang.org/pkg/text/template/)

I couldnt find it in documentation (https://golang.org/pkg/text/template/)

推荐答案

由于Go模板没有运算符,因此无法使用运算符来连接字符串.

There is not a way to concatenate strings with an operator because Go templates do not have operators.

使用问题中所示的 printf 函数,或将调用合并到单个模板表达式中:

Use the printf function as shown in the question or combine the calls in a single template expression:

{{ TestFunc (printf "%s%s" "x" "y") }}

如果您始终需要为TestFunc参数连接字符串,请编写TestFunc来处理串联:

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

这篇关于是否有连接字符串的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆