Hiểu về byte và rune trong Golang

tại sao Golang lại có 2 kiểu dữ liệu byte và rune


// byte is an alias for uint8 and is equivalent to uint8 in all ways. It is
// used, by convention, to distinguish byte values from 8-bit unsigned
// integer values.
type byte = uint8

// rune is an alias for int32 and is equivalent to int32 in all ways. It is
// used, by convention, to distinguish character values from integer values.
type rune = int32

Thực ra byte và rune là 2 kiểu alias của uint8 và int32

byte nó đại diện cho các ký tự không dấu
rune nó đại diện cho các ký tự unicode nên nó có khoảng rộng hơn byte

Ví dụ bạn có 2 chuỗi string như sau


s1 := "a123acb"

s2 := "a123acbaHôm nay quá đẹp"

arr1 := []byte(s1)
fmt.Printf("%v \n",arr1)

arr2 := []rune(s2)
fmt.Printf("%v",arr2)

Như vậy khi bạn ép kiểu thì thao tác sẽ không bị mất dữ liệu









Comments

Popular posts from this blog

Fixing the DeepSpeed Import Error While Fine-Tuning the Qwen Model

Amazon Linux 2023 - User data configuration for launch templates to connect to the EKS cluster

How to create ISM policy and rotate logs in opensearch