Go byte (byte) & character (rune)

byte

By bytedefining a byte, must use single quotes wrap direct print output bytes ascii code is required by formatting the output
byte is uint8 nicknames used primarily to distinguish between byte and byte unsigned integer two types
example:

func main() {
    var a byte
    fmt.Printf("%v, type: %T, char: %c", a, a, a)
}

Output:

0, type: uint8, char: 

rune

By runedefinition of a character, the character must use single quotes to wrap
rune int32 nickname is used primarily to differentiate rune integer of two types of characters and
Examples:

func main() {
    var a rune
    fmt.Printf("%v, type: %T, char: %c\n", a, a, a)
}

Output:

0, type: int32, char: 

byte & rune

byteRepresents a byte, English characters, etc. may represent one byte character, character occupies more than one byte can not be properly represented, for example, occupy three-byte characters
runerepresent a character, a character used to represent any

Example:

func main() {
    a := "你好,hello"
    b := []byte(a)
    c := []rune(a)
    fmt.Printf("b: %v\ntype: %T\n\nc: %v\ntype: %T", b, b, c, c)
}

Output:

b: [228 189 160 229 165 189 239 188 140 104 101 108 108 111]
type: []uint8

c: [20320 22909 65292 104 101 108 108 111]
type: []int32

It can be seen and can not be resolved byte characters exceeds 1 byte correctly, you need to use rune

Change

can convert between byte and rune, turn rune byte can not go wrong when
a problem occurs when the rune but turned byte:
If the character rune represented only takes a character, no more than uint8 can not go wrong when; direct conversion exceeds unable to compile, by referring to the conversion, but the excess will be discarded bits, the result of an error occurs
example:

func main() {
    char := '你'
    v1 := rune(char)
    v2 := byte(char)
    s1 := strconv.FormatInt(int64(v1), 2)
    s2 := strconv.FormatInt(int64(v2), 2)
    fmt.Printf("v1: %c, type: %T, %v\n", v1, v1, s1)
    fmt.Printf("v2: %c, type: %T, %v\n", v2, v2, s2)
}

Output:

v1: 你, type: int32, 100111101100000
v2: `, type: uint8, 1100000

Guess you like

Origin www.cnblogs.com/dbf-/p/12075186.html