← 中文资源

简体中文版本

match 表驱动摩斯码编解码

按字符 match 查表把字母编成点划码、再逐符号 match 解回原文:单词间隙用斜杠分隔,未知符号被 filter_map 丢弃,往返一致。

阅读英文原文

实现说明

承担主要工作的是函数 encode_morse、decode_morse、main。 match 一条一条覆盖值的形态——不会意外落到默认分支上。

使用要点

  • main 按顺序串起 encode_morse、decode_morse;运行文件就会把这个流程跑一遍。

常见问题

「match 表驱动摩斯码编解码」这个示例怎么运行?

文件自包含:直接运行,没有需要预先安装的依赖。

入口签名:fn encode_morse(text: &str) -> String

核心语句

.filter_map(|sym| match sym {
    ".-" => Some('A'), "-..." => Some('B'), "-.-." => Some('C'),
    "-.." => Some('D'), "." => Some('E'), "..-." => Some('F'),
    "/" => Some(' '),
    _ => None,
})
.filter_map(|c| match c {
    'A' => Some(".-"), 'B' => Some("-..."), 'C' => Some("-.-."),
    'D' => Some("-.."), 'E' => Some("."), 'F' => Some("..-."),
    ' ' => Some("/"),
    _ => None,
})

代码示例

fn encode_morse(text: &str) -> String {
    text.chars()
        .filter_map(|c| match c {
            'A' => Some(".-"), 'B' => Some("-..."), 'C' => Some("-.-."),
            'D' => Some("-.."), 'E' => Some("."), 'F' => Some("..-."),
            ' ' => Some("/"),
            _ => None,
        })
        .collect::<Vec<&str>>()
        .join(" ")
}

fn decode_morse(code: &str) -> String {
    code.split(' ')
        .filter_map(|sym| match sym {
            ".-" => Some('A'), "-..." => Some('B'), "-.-." => Some('C'),
            "-.." => Some('D'), "." => Some('E'), "..-." => Some('F'),
            "/" => Some(' '),
            _ => None,
        })
        .collect()
}

fn main() {
    let message = "DEAD BEEF";
    let encoded = encode_morse(message);
    println!("{message} -> {encoded}");
    let decoded = decode_morse(&encoded);
    println!("{encoded} -> {decoded}");
}