好好爱自己!

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

 

 

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

 

 

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]
posted @   立志做一个好的程序员  阅读(118)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2019-04-25 Translate Angular >=4 with ngx-translate and multiple modules
2019-04-25 jquery的deferred使用详解
2018-04-25 Why is chkconfig no longer available in Ubuntu?
2018-04-25 drag-html
2017-04-25 【转】配置windows路由表,使电脑同时连接内网外网方法
2017-04-25 局域网
2017-04-25 javascript 閉包

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示