dtdr84101 2018-03-02 02:54
浏览 811
已采纳

Golang中的'range str'和'range [] rune(str)'之间有什么区别

range str https://play.golang.org/p/I1JCUJnN41h

range []rune(str) https://play.golang.org/p/rJvyHH6lkl_t

I got the same results, are they the same? which one is better?

  • 写回答

2条回答 默认 最新

  • doujiaochan7317 2018-03-02 03:21
    关注

    Yes there is a difference. Given

    for i, c := range v {
    

    c will be the same whether v is a string or a rune slice, but i will vary if the string contains multibyte characters.

    String Indexing

    Strings are sequences of bytes and indexing is appropriate to a slice of bytes. Unless you are intentionally reading or manipulating bytes instead of code points or characters, or are sure your input contains no multibyte characters, wherever you are inclined to index a string you should use a rune slice instead.

    Range Loops are Special

    for i, c := range str {
    

    Range loops over strings are special. Instead of treating the string simply as a slice of bytes, range treats the string partly like a slice of bytes and partly like a slice of runes.

    The i will be the byte index of the beginning of the code point. The c will be a rune that can contain more than one byte. This means i can increase by more than one in an iteration because the prior code point was a multibyte character.

    Besides the axiomatic detail that Go source code is UTF-8, there's really only one way that Go treats UTF-8 specially, and that is when using a for range loop on a string. We've seen what happens with a regular for loop. A for range loop, by contrast, decodes one UTF-8-encoded rune on each iteration. Each time around the loop, the index of the loop is the starting position of the current rune, measured in bytes, and the code point is its value.

    See more in the official Go Blog post the above is excerpted from: Strings, bytes, runes and characters in Go

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写