zoukankan      html  css  js  c++  java
  • Go语言中的byte和rune区别、对比

    Go语言中byterune实质上就是uint8int32类型。byte用来强调数据是raw data,而不是数字;而rune用来表示Unicodecode point。参考规范

    uint8       the set of all unsigned  8-bit integers (0 to 255)
    int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
    
    byte        alias for uint8
    rune        alias for int32
    

    可以通过下面程序验证:

    package main
    
    import "fmt"
    
    func byteSlice(b []byte) []byte {
        return b
    }
    
    func runeSlice(r []rune) []rune {
        return r
    }
    
    func main() {
        b := []byte{0, 1}
        u8 := []uint8{2, 3}
        fmt.Printf("%T %T 
    ", b, u8)
        fmt.Println(byteSlice(b))
        fmt.Println(byteSlice(u8))
    
        r := []rune{4, 5}
        i32 := []int32{6, 7}
        fmt.Printf("%T %T 
    ", r, i32)
        fmt.Println(runeSlice(r))
        fmt.Println(runeSlice(i32))
    }
    

    执行结果如下:

    []uint8 []uint8
    [0 1]
    [2 3]
    []int32 []int32
    [4 5]
    [6 7]


    package main
    
    import (
        "fmt"
    )
    
    func main() {
        var indexRuneTests = []struct {
            s    string
            rune rune
            out  int
        }{
            //string用反引号能换行, 但不支持转义, rune是一个uint32,即一个unicode字符
            {`as
    
            df`, 'A', 2},
            //用双引号不能换行, 但支持转义如"
    	..",  rune是一个uint32,即一个unicode字符
            {"some_text
    =some_value", '=', 9},
            {"☺a", '', 3},
            {"a☻☺b", '', 4},
        }
    
        fmt.Println("Hello, playground",indexRuneTests)
    }
    Hello, playground [{as
    
            df 65 2} {some_text
    =some_value 61 9} {☺a 9786 3} {a☻☺b 9786 4}]

    参考资料:
    Difference between []uint8 && []byte (Golang Slices)

  • 相关阅读:
    ZOJ 2158 Truck History
    Knight Moves (zoj 1091 poj2243)BFS
    poj 1270 Following Orders
    poj 2935 Basic Wall Maze (BFS)
    Holedox Moving (zoj 1361 poj 1324)bfs
    ZOJ 1083 Frame Stacking
    zoj 2193 Window Pains
    hdu1412{A} + {B}
    hdu2031进制转换
    openjudge最长单词
  • 原文地址:https://www.cnblogs.com/sunsky303/p/9764910.html
Copyright © 2011-2022 走看看