This is a creation in Article, where the information may have evolved or changed.
A pit of strings in Golang this blog post describes the difference between a string in Golang and a string in C:the string in C is a \x0
sequence of bytes ending with, and the string in Golang is stricter, not judged by the \x0
end , but computes all the bytes in the value of the string variable.
The string in Golang is printed, because \x0
it is not a printable character, so there is no difference between the strings in C and the print. However, in some functions that require the string to be computed by byte, this can cause problems. The common practice is to iterate over the string and get only the valid bytes in the byte sequence.
We can write a function to do this, or we can use the library in the Golang standard library bytes
. The bytes
Library provides []byte
operations on types that provide interfaces that are similar to the string
interfaces provided by the type.
bytes
Provides a Compare、Count、Equal、Index、Join、Split、Replace
function that is directly targeted []byte
to a type. There is also an important Buffer
class that treats the []byte
type as a buffer, providing a convenient operation for the buffer: the 读、写、和string/rune之间的转换、迭代
function.
In the bytes
library, there is a Trim
series of functions, its function is to []byte
cut the type, remove the unwanted parts.
func Trim(s []byte, cutset string) []bytefunc TrimFunc(s []byte, f func(r rune) bool) []bytefunc TrimLeft(s []byte, cutset string) []bytefunc TrimLeftFunc(s []byte, f func(r rune) bool) []bytefunc TrimPrefix(s, prefix []byte) []bytefunc TrimRight(s []byte, cutset string) []bytefunc TrimRightFunc(s []byte, f func(r rune) bool) []bytefunc TrimSpace(s []byte) []bytefunc TrimSuffix(s, suffix []byte) []byte
We need to use the TrimRight
function to remove the non-printable characters from the byte sequence \x0
, preserving only what is needed:
package mainimport ( "bytes" "fmt")func main() { var a [10]byte = [10]byte{1, 2, 3} fmt.Printf("%q\n", a) // 将数组a转换为切片 b := a[:] // 去除切片尾部的所有0 c := bytes.TrimRight(b, "\x00") fmt.Printf("%q\n", c)}