首页 > 其他 > 详细

【转】Is there anyway to create null terminated string in Go

时间:2021-04-25 23:15:17      阅读:24      评论:0      收藏:0      [点我收藏+]

 

 

--------------------------------

 

 

15

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

3 Answers

39
 

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]

【转】Is there anyway to create null terminated string in Go

原文:https://www.cnblogs.com/oxspirt/p/14701425.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!