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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?