2016-06-24 13 views
5

Gibt es in Go überhaupt eine nullterminierte string?Gibt es in Go überhaupt eine nullterminierte Zeichenfolge?

Was ich derzeit versuche a:="golang\0" aber es zeigt Kompilierungsfehler:

non-octal character in escape sequence: " 
+0

Wenn Sie es brauchen, verwenden Sie '0' insted, um Ihre Arbeit zu erledigen. – ameyCU

+0

Siehe: https://golang.org/ref/spec#String_literals. – Volker

+1

NUL wird in Strings als '\ x00' maskiert. Die Sprache stellt auch keine NUL-terminierten Strings zur Verfügung, also .. ja, Sie müssen jede Zeichenkette ändern. – toqueteos

Antwort

14

Spec: String literals:

The text between the quotes forms the value of the literal, with backslash escapes interpreted as they are in rune literals (except that \' is illegal and \" is legal), with the same restrictions. The three-digit octal (\nnn) and two-digit hexadecimal (\xnn) escapes represent individual bytes of the resulting string; all other escapes represent the (possibly multi-byte) UTF-8 encoding of individual characters.

So \0 ist eine illegale Sequenz, haben Sie 3 Oktalziffern verwenden:

s := "golang\000" 

Oder verwenden Sie hex Code (2 Hexadezimalzeichen):

s := "golang\x00" 

Oder eine Unicode-Sequenz (4 Hexadezimalzeichen):

s := "golang\u0000" 

Beispiel:

s := "golang\000" 
fmt.Println([]byte(s)) 
s = "golang\x00" 
fmt.Println([]byte(s)) 
s = "golang\u0000" 
fmt.Println([]byte(s)) 

Output: Alle Ende mit einem 0-Codebyte (Probieren Sie es auf der Go Playground).

[103 111 108 97 110 103 0] 
[103 111 108 97 110 103 0] 
[103 111 108 97 110 103 0] 
+0

Danke icza, es hat wirklich geholfen. –