This is a creation in Article, where the information may have evolved or changed.
The string is a sequence of immutable bytes ( byte
), and the default value is "" instead of nil
.
Use the original string () defined by "'" raw strubg
to support cross-line. string support !=、==、<、>、+、+=
operators. Allows access to an array of bytes with an index number, but cannot get an element address.
There for
are two ways to use the traversal string byte
rune
.
Transformation
Modify the string, convert it to a mutable type ( []byte
or []rune
), and then convert it back when it is finished. This process will reallocate memory and replicate the data. This conversion process has a certain performance penalty. For better performance, you can use a "non-secure" approach to improve.
func bytesToString(bs []byte) string { return *(*string)(unsafe.Pointer(&bs))}
can also be converted in the same way string
as []byte
. Just the resulting byte sequence is not modifiable, and when trying to modify it, you get an error like this:
unexpected fault address 0x1066146fatal error: fault[signal SIGBUS: bus error code=0x2 addr=0x1066146 pc=0x104bff0]
Dynamically Building strings
+
when stitching strings, memory is redistributed every time. Performance will be very poor when stitching over multiple strings.
The improved idea is to allocate enough memory space to reduce the number of memory allocations. The common method is a strings.Join
function, which is implemented as follows:
func Join(a []string, sep string) string { if len(a) == 0 { return "" } if len(a) == 1 { return a[0] } n := len(sep) * (len(a) - 1) for i := 0; i < len(a); i++ { n += len(a[i]) } b := make([]byte, n) bp := copy(b, a[0]) for _, s := range a[1:] { bp += copy(b[bp:], sep) bp += copy(b[bp:], s) } return string(b)}
Combining the previous content, you can Join
modify the function slightly, reducing the memory allocation and the content copy operation.
func Join(a []string, sep string) string { …… return toString(b)}