Rust“线程'main'对'None'值的'Option :: unwrap()`感到恐慌”

时间:2018-11-12 23:28:51

标签: rust

我正在学习一些防锈方法,并从密码学家https://cryptopals.com/sets/1/challenges/1中进行了挑战,我想将十六进制String转换为Base64 String。

因此,我编写了该程序,但是执行该程序时会引发错误。

use std::io;

fn main() {
    let mut text_to_convert = String::new();
    println!("Please enter the string to convert!");
    io::stdin().read_line(&mut text_to_convert).expect("Failed to read line");

    println!("Base64: {}", string_to_base64(text_to_convert));
}

fn string_to_base64(text: String) -> String {
    let mut base64_string = String::new();
    for c in text.chars() {
        base64_string.push_str(&hex_to_bits(c));
    }
    base64_string
}

fn hex_to_bits(c: char) -> String {
    let mut result = String::new();
    let x = c.to_digit(16).unwrap();
    let mut tmp = x;
    while tmp != 0 {
        result = (tmp % 2).to_string() + &result;
        tmp = tmp/2;
    }
    while result.len() < 4 {
        result = "0".to_string() + &result;
    }
    print!("{}", result);
    result
}

要学习这种语言,我不想使用板条箱,而是自己编程所需的功能。所以我从一个十六进制到位的转换器开始。

启动程序时出现此错误:

cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/nr1`
Please enter the string to convert!
F
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value',     /checkout/src/libcore/option.rs:335:21
note: Run with `RUST_BACKTRACE=1` for a backtrace.
1010

0 个答案:

没有答案