char_indices Yields Byte Offsets

Walk chars with byte offsets using char_indices, where multi-byte characters push offsets ahead of ordinal positions and slicing needs offsets.

RustData Integrity

Code

rustsnippet
16 lines
fn main() {
    let label = "héllo ✦ rust";

    // char_indices 产出 (字节偏移, 字符):多字节字符让偏移跑在序号前面
    for (offset, ch) in label.char_indices().take(4) {
        println!("{offset}: {ch}");
    }

    // 序号 2 的字符偏移已是 3(é 占 2 字节)
    let at = label.char_indices().nth(2);
    println!("third char: {at:?}");

    // 字节偏移可用于安全切片(必须落在字符边界)
    let (idx, _) = label.char_indices().nth(2).unwrap();
    println!("prefix: {}", &label[..idx]);
}

What the code does

Count the function main as the entire surface area of char_indices Yields Byte Offsets.

The file repeats itself only inside for (offset, ch) in label.char_indices().take(4).

Using it

Running the file prints labeled results such as third char:, prefix: — each operation’s effect is visible in the output.

Key statements

let (idx, _) = label.char_indices().nth(2).unwrap();
for (offset, ch) in label.char_indices().take(4) {
println!("{offset}: {ch}");
}

Interactive Tools for This Topic

FAQ

What does char_indices Yields Byte Offsets print when run?
Run it as a complete program — the output lines carry labels such as `third char:`, `prefix:`.