Slice Strings Only At Char Boundaries
Indexing a &str by bytes panics off char boundaries; get returns None instead, and is_char_boundary backs a safe truncation helper.
Code
fn truncate_safe(s: &str, max_bytes: usize) -> &str {
// strings 只能在 char boundaries 上切片:直接索引会 panic,get 返回 None
match s.get(..max_bytes) {
Some(prefix) => prefix,
None => {
// 逐字节回退,直到落在字符边界
let mut end = max_bytes.min(s.len());
while end > 0 && !s.is_char_boundary(end) {
end -= 1;
}
&s[..end]
}
}
}
fn main() {
// é 占 2 字节、☕ 与 黑 各占 3 字节:总长 13 字节
let label = "café ☕ 黑";
println!("bytes = {}", label.len());
println!("get(..4) is none: {}", label.get(..4).is_none()); // 4 落在 é 中间
println!("get(..6) ok: {}", label.get(..6).unwrap()); // "café "
println!("truncate 8: {}", truncate_safe(label, 8)); // 回退到边界 6
let owned = label.to_string();
println!("owned first 6: {}", &owned[..6]); // String 的边界规则相同
}What the code does
Slice Strings Only At Char Boundaries keeps everything in the functions truncate_safe and main.
Repetition is confined to while end > 0 && !s.is_char_boundary(end) — the rest of the file is straight-line. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.
Using it
The main signature reads fn truncate_safe(s: &str, max_bytes: usize) -> &str
The demo output is labeled (bytes =, get(..4) is none:, get(..6) ok:), so every printed line maps back to its originating operation.
The sequence truncate_safe lives in main; running the file triggers it.
Key statements
match s.get(..max_bytes) {
Some(prefix) => prefix,
None => {
// 逐字节回退,直到落在字符边界
let mut end = max_bytes.min(s.len());
while end > 0 && !s.is_char_boundary(end) {
end -= 1;
}
&s[..end]
}
}
Interactive Tools for This Topic
FAQ
- What does Slice Strings Only At Char Boundaries print when run?
- Run it as a complete program — the output lines carry labels such as `bytes =`, `get(..4) is none:`, `get(..6) ok:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.