Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to create null terminated string in Go?

Is there anyway to create 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: "
like image 332
Yash Srivastava Avatar asked Jun 24 '16 06:06

Yash Srivastava


People also ask

How do you make a null-terminated string?

To create a null-terminated string, code: String Y delimited by size X'00' delimited by size into N. To concatenate two null-terminated strings, code: String L delimited by x'00' M delimited by x'00' X'00' delimited by size into N.

Are Go strings null-terminated?

GO only allows limited operations on string as it is immutable [3] and represented as a byte-slice. Unlike C/C++, string in Go is not null-terminated.

How do you add null in Terminator?

This: buf[0] = '\0'; puts a null terminator right on the start of the string, overriding c (which you just assigned to buf[0] ).

Does Strcpy add null terminator?

The strcpy() function copies string2, including the ending null character, to the location that is specified by string1.


1 Answers

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]
like image 173
icza Avatar answered Oct 07 '22 11:10

icza