无论如何,要在Go中创建以null结尾的字符串? [英] Is there anyway to create null terminated string in Go?

查看:487
本文介绍了无论如何,要在Go中创建以null结尾的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在Go中创建以null结尾的 string



我目前正在尝试的是 a:=golang\0但它显示编译错误:

 转义序列中的非八进制字符:


解决方案

规范:字符串文字:


引号之间的文本形成文字的值,反斜杠转义解释为它们在符文文字(除了 \'是非法的并且 \是合法的),相同的限制。三位八进制( \\\
nn
)和两位十六进制( \xnn )转义表示单个字节由此产生的字符串;所有其他转义表示单个字符的UTF-8编码(可能为多字节)。

因此 \\ \\ 0 是一个非法序列,您必须使用3个八进制数字:

  s:= golang\000

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

  s:=golang\x00

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

  s:=golang\\\

示例:

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

输出:全部以0代码字节结尾(可以在 Go

  [103 111 108 97 110 103 0] 
[103 111 108 97 110 103 0]
[103 1 11 108 97 110 103 0]


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

解决方案

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]

这篇关于无论如何,要在Go中创建以null结尾的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆