2016-06-24 11 views
5

Czy jest mimo to utworzenie wartości zerowej zakończonej string w programie Go?Czy istnieje mimo to utworzenie łańcucha zakończonego znakiem NUL w programie Go?

Co Obecnie próbuję to a:="golang\0" ale to pokazuje błąd kompilacji:

non-octal character in escape sequence: " 
+0

Jeśli jest to potrzebne, należy wpisać '0', aby wykonać pracę. – ameyCU

+0

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

+1

NUL jest unikany jako '\ x00' w ciągach. Ponadto, język nie zawiera łańcuchów zakończonych znakiem NUL, więc ... tak, jesteś zmuszony modyfikować każdy ciąg znaków. – toqueteos

Odpowiedz

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.

Więc \0 jest nielegalne sekwencja, trzeba użyć 3 cyfry ósemkowe:

s := "golang\000" 

Lub użyj heksadecymalny (Cyfry 2 hex) Kod:

s := "golang\x00" 

lub sekwencję unikodową (4 cyfry hex):

s := "golang\u0000" 

przykład:

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

wyjściowa: wszystkie kończą się bajtu 0 kodu (wypróbuj go na Go Playground).

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

Dzięki icza, to naprawdę pomogło. –

Powiązane problemy