实现说明
用 split_once 解析键值对可以归结为函数 main。
重复被限制在 for line in lines 里——其余代码按顺序各跑一遍。match 逐一列出值的可能形态,漏掉的分支编译器会拒绝。
使用要点
- 演示输出是带标签的(
scheme=、no scheme),每个操作都会留下自己的一行标注。
常见问题
运行「用 split_once 解析键值对」会打印什么?
整个文件跑完,输出行以 scheme=、no scheme 这类前缀开头。
核心语句
match target.rsplit_once("://") {
Some((scheme, rest)) => println!("scheme={scheme} rest={rest}"),
None => println!("no scheme"),
}
match line.split_once('=') {
Some((key, value)) => println!("{key} -> {value:?}"),
None => println!("{line:?} -> skipped: no '='"),
}
代码示例
fn main() {
// split_once 只在第一个分隔符处切一刀,返回 Option<(前, 后)>
let lines = [
"timeout=30s",
"retries=5",
"proxy=http://10.0.0.1:8080",
"novalue-here",
];
for line in lines {
match line.split_once('=') {
Some((key, value)) => println!("{key} -> {value:?}"),
None => println!("{line:?} -> skipped: no '='"),
}
}
// URL 里带 '://':split_once 会切错位置,rsplit_once 从右侧切才保得住 scheme
let target = "https://api.example.com/v2/users?limit=5";
match target.rsplit_once("://") {
Some((scheme, rest)) => println!("scheme={scheme} rest={rest}"),
None => println!("no scheme"),
}
}