Go Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How it works...

The steps 1 - 5 cover the use of the bytes package Buffer as a performance-friendly solution to string concatenation. The Buffer structure implements the WriteString method, which could be used to effectively concatenate the strings into an underlying byte slice.

There is no need to use this improvement in all situations, just think about this in cases where the program is going to concatenate a big number of strings (for example, in-memory CSV exports and others).

The built-in copy function presented in steps 6 - 8 could be used to accomplish the string concatenation. This method requires some assumption about the final string length, or it could be done on the fly. However, if the capacity of the buffer, where the result is written, is smaller than the sum of the already written part and the string to be appended, the buffer must be expanded (usually by the allocation of a new slice with bigger capacity).