实现说明
凯撒位移的字符环运算可以归结为函数 shift、main。
match 逐一列出值的可能形态,漏掉的分支编译器会拒绝。
使用要点
- 演示输出是带标签的(
cipher:、decoded:、roundtrip ok:),每个操作都会留下自己的一行标注。 main的演示流程是shift——跑一遍文件,这条流程从头到尾可见。
常见问题
运行「凯撒位移的字符环运算」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 cipher:、decoded:、roundtrip ok: 这类标签。
主要签名是 fn shift(text: &str, k: i8) -> String
核心语句
.map(|c| match c {
'a'..='z' => {
let pos = (c as u8 - b'a') as i32;
// rem_euclid 把位移折进 0..26 的环:负位移也能正确回读
let ring = (pos + k as i32).rem_euclid(26);
(b'a' + ring as u8) as char
}
_ => c,
})
代码示例
// Caesar cipher 只旋转小写字母,其余字符原样保留
fn shift(text: &str, k: i8) -> String {
text.chars()
.map(|c| match c {
'a'..='z' => {
let pos = (c as u8 - b'a') as i32;
// rem_euclid 把位移折进 0..26 的环:负位移也能正确回读
let ring = (pos + k as i32).rem_euclid(26);
(b'a' + ring as u8) as char
}
_ => c,
})
.collect()
}
fn main() {
let plain = "attack at dawn";
let cipher = shift(plain, 3);
println!("cipher: {cipher}");
let decoded = shift(&cipher, -3);
println!("decoded: {decoded}");
println!("roundtrip ok: {}", decoded == plain);
}