golang how does the rune() function work

前端 未结 2 1950
予麋鹿
予麋鹿 2020-11-28 16:40

I came across a function posted online that used the rune() function in golang, but I am having a hard time looking up what it is. I am going through the tutori

相关标签:
2条回答
  • 2020-11-28 17:18

    As stated in @Michael's first-rate comment fmt.Println([]rune("foo")) is a conversion of a string to a slice of runes []rune. When you convert from string to []rune, each utf-8 char in that string becomes a Rune. See https://stackoverflow.com/a/51611567/12817546. Similarly, in the reverse conversion, when converted from []rune to string, each rune becomes a utf-8 char in the string. See https://stackoverflow.com/a/51611567/12817546. A []rune can also be set to a byte, float64, int or a bool.

    package main
    
    import (
        . "fmt"
    )
    
    func main() {
        r := []rune("foo")
        c := []interface{}{byte(r[0]), float64(r[0]), int(r[0]), r, string(r), r[0] != 0}
        checkType(c)
    }
    
    func checkType(s []interface{}) {
        for k, _ := range s {
            Printf("%T %v\n", s[k], s[k])
        }
    }
    

    byte(r[0]) is set to “uint8 102”, float64(r[0]) is set to “float64 102”,int(r[0]) is set to “int 102”, r is the rune” []int32 [102 111 111]”, string(r) prints “string foo”, r[0] != 0 and shows “bool true”.

    []rune to string conversion is supported natively by the spec. See the comment in https://stackoverflow.com/a/46021588/12817546. In Go then a string is a sequence of bytes. However, since multiple bytes can represent a rune code-point, a string value can also contain runes. So, it can be converted to a []rune , or vice versa. See https://stackoverflow.com/a/19325804/12817546.

    Note, there are only two built-in type aliases in Go, byte (alias of uint8) and rune (alias of int32). See https://Go101.org/article/type-system-overview.html. Rune literals are just 32-bit integer values. For example, the rune literal 'a' is actually the number "97". See https://stackoverflow.com/a/19311218/12817546. Quotes edited.

    0 讨论(0)
  • 2020-11-28 17:20

    rune is a type in Go. It's just an alias for int32, but it's usually used to represent Unicode points. rune() isn't a function, it's syntax for type conversion into rune. Conversions in Go always have the syntax type() which might make them look like functions.

    The first bit of code fails because conversion of strings to numeric types isn't defined in Go. However conversion of strings to slices of runes/int32s is defined like this in language specification:

    Converting a value of a string type to a slice of runes type yields a slice containing the individual Unicode code points of the string. [golang.org]

    So your example prints a slice of runes with values 102, 111 and 111

    0 讨论(0)
提交回复
热议问题