douqiao8032 2016-06-24 06:57
浏览 289
已采纳

无论如何,在Go中创建以null结尾的字符串吗?

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: "
  • 写回答

1条回答 默认 最新

  • doushi5024 2016-06-24 08:06
    关注

    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 ( nn) 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]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧