2016-06-24 116 views
5

Goでnullを作成する方法はありますか。stringGoでnull終端文字列を作成する方法はありますか?

私は現在しようとしていることa:="golang\0"ですが、それが表示されているコンパイルエラー:

non-octal character in escape sequence: " 
+0

必要な場合は、「0」instedを使用して作業を完了してください。 – ameyCU

+0

参照:https://golang.org/ref/spec#String_literals。 – Volker

+1

NULは文字列で '\ x00'としてエスケープされます。また、言語はNULで終了する文字列を提供しないので、すべての文字列を変更する必要があります。 – toqueteos

答えて

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.

ので\0は違法配列である、あなたは3桁の8進数を使用する必要があります。

s := "golang\000" 

または16進数コード(2進数字):

s := "golang\x00" 

またはUnicodeシーケンス(4進数字):

s := "golang\u0000" 

例:

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

出力:0コードバイトを有するすべてのエンド(Go Playgroundで試してみてください)。

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

iczaありがとう、本当に助けてくれました。 –

関連する問題