Reference: blog1, blog2, blog_3, blog_4
Definition
A string is a slice of bytes in Go.
1 | string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. A string may be empty, but not nil. Values of string type are immutable. |
Base Data Structure of String in Go
String in Go is C Struct, string is a wrapper of byte
sequence. We can realyyy view string as immutable byte slice.
1 | type _string struct { |
literal String| Raw String | Multi Line String
Go support two styles of string literals, the double-quote style and the back-quote style(raw string literalss).
Literal String: created with double quotes, escape sequence is sensitive, such as \n
, \r
;
Raw String: created with back-quote, escape sequence is insensitive.
Multi Line String: create with bak-quote with multi line, escape sequence is insensitive.
1 | package main |
Some Fact with String
- String values can be used as constants (along with boolean and all kinds of numeric values).
- Go supports two styles of string literals, the double-quote style (or interpreted literals) and the back-quote style (or raw string literals).
- The zero values of string types are blank strings, which can be represented with
""
or ```` in literal. - Strings can be concatenated with
+
and+=
operators. - String types are all comparable (by using the
==
and!=
operators). And like integer and floating-point values, two values of the same string type can also be compared with>
,<
,>=
and<=
operators. When comparing two strings, their underlying bytes will be compared, one byte by one byte. If one string is a prefix of the other one and the other one is longer, then the other one will be viewed as the larger one.
1 | package main |
- Like Java, the contents (underlying bytes) of string values are immutable. The lengths of string values also can’t be modified separately. An addressable string value can only be overwritten as a whole by assigning another string value to it.
- The built-in
string
type has no methods (just like most other built-in types in Go), but we can- use functions provided in the
strings
standard package to do all kinds of string manipulations. - call the built-in
len
function to get the length of a string (number of bytes stored in the string). - use the element access syntax
aString[i]
introduced in container element accesses to get the *i**th*byte
value stored inaString
. The expressionaString[i]
is not addressable. In other words, valueaString[i]
can’t be modified. - use the subslice syntax
aString[start:end]
to get a substring ofaString
. Here,start
andend
are both indexes of bytes stored inaString
.
- use functions provided in the
- For the standard Go compiler, the destination string variable and source string value in a string assignment will share the same underlying byte sequence in memory. The result of a substring expression
aString[start:end]
also shares the same underlying byte sequence with the base stringaString
in memory.
1 | package main |
Operation With String
Compare String in Go
As mentioned above, when comparing two strings, their underlying bytes will be compared, one byte by one byte, If one string is the prefix of another string, then the longer one viewed as the larger one. While Go compilers make the following optimizations for string comparisons.
- For
==
and!=
comparison, if the length of the compared string is not equal, then the two strings must be not equal. - If their underlying bytes sequence pointers are equal, then the comparision result is the same as comparing the length of two strings.
So for two equal strings, the time complexity of comparing them depend on whether or not their underlying byte sequence pointers are equal. If the two are equal, time complexity is O(1)
, otherwise is O(n)
.
As above mentioned, for the go standrad Go compiler, in a string value assignment, the destination string value and the source string will share the same underlying byte sequence in memory. So the cost of comparing the two strings becomes very small.
1 | package main |
1ms is 1000000ns! So please try to avoid comparing two long strings if they don’t share the same underlying byte sequence.
Loop Over String
- **Classic for : loop over bytes. **
- For range: loops over runes.
1 | package main |
String Join | String Split
Besides using the +
operator to concatenate strings, we can also use following ways to concatenate strings.
- The
Sprintf
/Sprint
/Sprintln
functions in thefmt
standard package can be used to concatenate values of any types, including string types. - Use the
Join
function in thestrings
standard package. - The
Buffer
type in thebytes
standard package (or the built-incopy
function) can be used to build byte slices, which afterwards can be converted to string values. - Since Go 1.10, the
Builder
type in thestrings
standard package can be used to build strings. Comparing withbytes.Buffer
way, this way avoids making an unnecessary duplicated copy of underlying bytes for the result string.
The standard Go compiler makes optimizations for string concatenations by using the +
operator. So generally, using +
operator to concatenate strings is convenient and efficient if the number of the concatenated strings is known at compile time.
String Related Conversion
String Conversion With Byte And Rune
- a string value can be explicitly converted to byte slice, and vice versa.
- a string value can be explicitly converted to rune slice, and vice versa.
In a conversion from a rune slice to string, each slice element (a rune value) will be UTF-8 encoded as from one to four bytes and stored in the result string. If a slice rune element value is outside the range of valid Unicode code points, then it will be viewed as 0xFFFD
, the code point for the Unicode replacement character. 0xFFFD
will be UTF-8 encoded as three bytes (0xef 0xbf 0xbd
).
When a string is converted to a rune slice, the bytes stored in the string will be viewed as successive UTF-8 encoding byte sequence representations of many Unicode code points. Bad UTF-8 encoding representations will be converted to a rune value 0xFFFD
.
When a string is converted to a byte slice, the result byte slice is just a deep copy of the underlying byte sequence of the string. When a byte slice is converted to a string, the underlying byte sequence of the result string is also just a deep copy of the byte slice. A memory allocation is needed to store the deep copy in each of such conversions. The reason why a deep copy is essential is slice elements are mutable but the bytes stored in strings are immutable, so a byte slice and a string can’t share byte elements.
Please note, for conversions between strings and byte slices,
- illegal UTF-8 encoded bytes are allowed and will keep unchanged.
- the standard Go compiler makes some optimizations for some special cases of such conversions, so that the deep copies are not made.
Conversion Between Byte And Rune
Conversions between byte slices and rune slices are not supported directly in Go, We can use the following ways to achieve this goal:
- use string values as a hop. This way is convenient but not very efficient, for two deep copies are needed in the process.
- use the functions in unicode/utf8 standard package.
- use the
Runes
function in the bytes standard package to convert a[]byte
value to a[]rune
value. There is not a function in this package to convert a rune slice to byte slice.
1 | package main |
Compiler Optimizations for Conversions Between Strings and Byte Slices
Above has mentioned that the underlying bytes in the conversions between strings and byte slices will be copied. The standard Go compiler makes some optimizations, which are proven to still work in Go Toolchain 1.18, for some special scenarios to avoid the duplicate copies. These scenarios include:
- a conversion (from string to byte slice) which follows the
range
keyword in afor-range
loop. - a conversion (from byte slice to string) which is used as a map key in map element retrieval indexing syntax.
- a conversion (from byte slice to string) which is used in a comparison.
- a conversion (from byte slice to string) which is used in a string concatenation, and at least one of concatenated string values is a non-blank string constant.
1 | package main |
Note, the last line might not output value
if there are data races in evaluating string(key)
. However, such data races will never cause panics.
1 | package main |