32

How to create a null-terminated string in Go?

What I'm currently trying is a:="golang\0" but it is showing compilation error:

non-octal character in escape sequence: "
3
  • If you need it, use 0 insted to get your work done. Commented Jun 24, 2016 at 7:03
  • See: golang.org/ref/spec#String_literals . Commented Jun 24, 2016 at 7:42
  • 3
    NUL is escaped as \x00 in strings. Also, the language doesn't provide NUL-terminated strings so.. yes, you are forced to modify every string. Commented Jun 24, 2016 at 8:05

3 Answers 3

59

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 is an illegal sequence, you have to use 3 octal digits:

s := "golang\000"

Or use hex code (2 hex digits):

s := "golang\x00"

Or a unicode sequence (4 hex digits):

s := "golang\u0000"

Example:

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

Output: all end with a 0-code byte (try it on the Go Playground).

[103 111 108 97 110 103 0]
[103 111 108 97 110 103 0]
[103 111 108 97 110 103 0]
Sign up to request clarification or add additional context in comments.

Comments

1

Another option is the ByteSliceFromString function:

package main

import (
   "fmt"
   "golang.org/x/sys/windows"
)

func main() {
   b, e := windows.ByteSliceFromString("golang")
   if e != nil {
      panic(e)
   }
   fmt.Printf("%q\n", string(b)) // "golang\x00"
}

Comments

1

@icza describes how to write a string literal with a null terminator. Use this code to add a null to the end of a string variable:

 s += string(rune(0))

Example:

s := "hello"
s += string(rune(0))
fmt.Printf("%q\n", s)  // prints "hello\x00"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.