无论如何在 Go 中创建空终止字符串?

Is there anyway to create null terminated string in Go?

有没有在 Go 中创建 null 终止的 string

我目前正在尝试的是 a:="golang[=12=]" 但它显示编译错误:

non-octal character in escape sequence: "

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.

所以[=19=]是一个非法序列,你必须使用3个八进制数字:

s := "golang[=10=]0"

或使用十六进制代码(2 个十六进制数字):

s := "golang\x00"

或 unicode 序列(4 个十六进制数字):

s := "golang\u0000"

示例:

s := "golang[=13=]0"
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]

另一个选项是 ByteSliceFromString 函数:

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"
}

@icza 介绍了如何编写带有空终止符的字符串文字。使用此代码将空值添加到字符串变量的末尾:

 s += string(rune(0))

示例:

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