Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an efficient way to concatenate strings

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/)

like image 463
Özgür Yalçın Avatar asked Jul 29 '17 13:07

Özgür Yalçın


People also ask

What is the correct way to concatenate the strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

What is the best way to concatenate strings in Java?

Using + Operator The + operator is one of the easiest ways to concatenate two strings in Java that is used by the vast majority of Java developers. We can also use it to concatenate the string with other data types such as an integer, long, etc.

What is the most efficient way to concatenate many strings together Python?

Practical Data Science using Python The best way of appending a string to a string variable is to use + or +=. This is because it's readable and fast. They are also just as fast.

Which is the fastest way to concatenate many strings in Java?

concat will typically be the fastest way to concat two String s (but do note null s).


1 Answers

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 }}
like image 96
Bayta Darell Avatar answered Oct 21 '22 10:10

Bayta Darell