Note that the first answer will only work with strings that have zero zero after the terminator zero; however, a valid C-style zero-terminated string ends at the first \0 , even if garbage follows it. For example, []byte{97,98,99,0,99,99,0} should be analyzed as abc , not abc^@cc .
To correctly analyze this, use string.Index as shown below to find the first \0 and use it to trim the original byte fragment:
package main import ( "fmt" "strings" ) func main() { label := []byte{97,98,99,0,99,99,0} s := label[:strings.Index(string(label), "\x00")] fmt.Println(string(s)) }
EDIT: printed the shortened version as []byte instead of string . Thanks @serbaut for the trick.
source share