dongou2019 2013-10-11 05:14
浏览 33
已采纳

什么是符文?

What is a rune in Go?

I've been googling but Golang only says in one line: rune is an alias for int32.

But how come integers are used all around like swapping cases?

The following is a function swapcase. What is all the <= and -?

And why doesn't switch have any arguments?

&& should mean and but what is r <= 'z'?

func SwapRune(r rune) rune {
    switch {
    case 'a' <= r && r <= 'z':
        return r - 'a' + 'A'
    case 'A' <= r && r <= 'Z':
        return r - 'A' + 'a'
    default:
        return r
    }
}

Most of them are from http://play.golang.org/p/H6wjLZj6lW

func SwapCase(str string) string {
    return strings.Map(SwapRune, str)
}

I understand this is mapping rune to string so that it can return the swapped string. But I do not understand how exactly rune or byte works here.

  • 写回答

7条回答 默认 最新

  • dpd2349 2013-10-11 05:58
    关注

    Rune literals are just 32-bit integer values (however they're untyped constants, so their type can change). They represent unicode codepoints. For example, the rune literal 'a' is actually the number 97.

    Therefore your program is pretty much equivalent to:

    package main
    
    import "fmt"
    
    func SwapRune(r rune) rune {
        switch {
        case 97 <= r && r <= 122:
            return r - 32
        case 65 <= r && r <= 90:
            return r + 32
        default:
            return r
        }
    }
    
    func main() {
        fmt.Println(SwapRune('a'))
    }
    

    It should be obvious, if you were to look at the Unicode mapping, which is identical to ASCII in that range. Furthermore, 32 is in fact the offset between the uppercase and lowercase codepoint of the character. So by adding 32 to 'A', you get 'a' and vice versa.

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名