实现说明
用 splitn 限段切分并保留余文可以归结为函数 main。
使用要点
- 每一步打印都带着自己的标签:
level=、message=、split all:。
常见问题
运行「用 splitn 限段切分并保留余文」会打印什么?
运行文件本身,level=、message=、split all: 这些前缀各对应一段演示逻辑。
核心语句
let none: Vec<&str> = line.splitn(0, ':').collect();
let greedy: Vec<&str> = line.split(':').collect();
let message = parts.next().unwrap_or("");
代码示例
fn main() {
// message format: level:module:message, and message itself may contain colons
let line = "WARN:auth:token expired: please relogin";
// splitn(3, ':'): at most 3 pieces, and everything past the limit stays verbatim (the remainder)
let mut parts = line.splitn(3, ':');
let level = parts.next().unwrap_or("");
let module = parts.next().unwrap_or("");
let message = parts.next().unwrap_or("");
println!("level={level} module={module}");
println!("message={message}");
// a plain split would shred message too; the contrast shows what the limit buys
let greedy: Vec<&str> = line.split(':').collect();
println!("split all: {greedy:?}");
// rsplitn cuts from the right: take the last field first and keep the rest as one piece
let mut tail = line.rsplitn(2, ':');
let last = tail.next().unwrap_or("");
let rest = tail.next().unwrap_or("");
println!("rest={rest}");
println!("last={last}");
// with limit 0, splitn yields nothing at all
let none: Vec<&str> = line.splitn(0, ':').collect();
println!("limit 0: {none:?}");
}