← 中文资源

简体中文版本

Char Encode UTF-8 缓冲区

用 char::encode_utf8 把字符写进固定 4 字节缓冲区,返回的切片长度就是该字符的 UTF-8 宽度。

阅读英文原文

实现说明

Char Encode UTF-8 缓冲区可以归结为函数 main。 驱动整个流程的是 for ch in samples 这一个循环。

使用要点

  • 每一步打印都带着自己的标签:matches bytes:、total utf8 bytes:、scratch width:。

常见问题

运行「Char Encode UTF-8 缓冲区」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 matches bytes:、total utf8 bytes:、scratch width: 标签标明各步骤。

核心语句

let total: usize = samples.iter().map(|ch| ch.len_utf8()).sum();

代码示例

fn main() {
    let samples = ['a', 'é', '世', '🎉'];

    for ch in samples {
        // char::encode_utf8 writes the UTF-8 bytes into the buffer
        let mut buffer = [0_u8; 4];
        let encoded = ch.encode_utf8(&mut buffer);
        println!("{ch:?} -> {} bytes {:?}", encoded.len(), encoded.as_bytes());
        println!("matches bytes: {}", encoded.as_bytes() == ch.to_string().as_bytes());
    }

    let total: usize = samples.iter().map(|ch| ch.len_utf8()).sum();
    println!("total utf8 bytes: {total}");
    println!("scratch width: {}", std::mem::size_of_val(&[0_u8; 4]));
}