Skip to content
On this page

Option 2: exercises/options/options2.rs

题目

rust
// options2.rs
//
// Execute `rustlings hint options2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

#[cfg(test)]
mod tests {
    #[test]
    fn simple_option() {
        let target = "rustlings";
        let optional_target = Some(target);

        // TODO: Make this an if let statement whose value is "Some" type
        word = optional_target {
            assert_eq!(word, target);
        }
    }

    #[test]
    fn layered_option() {
        let range = 10;
        let mut optional_integers: Vec<Option<i8>> = vec![None];

        for i in 1..(range + 1) {
            optional_integers.push(Some(i));
        }

        let mut cursor = range;

        // TODO: make this a while let statement - remember that vector.pop also
        // adds another layer of Option<T>. You can stack `Option<T>`s into
        // while let and if let.
        integer = optional_integers.pop() {
            assert_eq!(integer, cursor);
            cursor -= 1;
        }

        assert_eq!(cursor, 0);
    }
}

题目解析

题目中只有两个单元测试,首先来看simple_option函数:

  • target是一个类型为&str的不可变变量
  • optional_targettarget封装成了Option<&str>类型
  • 后面需要使用if let将结果赋给word,word与target进行比较
rust
#[test]
    fn simple_option() {
        let target = "rustlings";
        let optional_target = Some(target);

        // TODO: Make this an if let statement whose value is "Some" type
        word = optional_target {  
        if let Some(word) = optional_target { 
            assert_eq!(word, target);
        }
    }

第二个单元测试layered_option的逻辑如下:

  • 变量range是值为8的不可变变量
  • 变量optional_integers是类型为Vec<Option<i8>>类型的Vec,里面目前只有一个None
  • 循环从1到10,并将Some(i)放入optional_integers里面。
  • 变量cursor是值为8的可变变量。
  • 我们需要使用while let循环比对integer和cursor的值
rust
#[test]
    fn layered_option() {
        let range = 10;
        let mut optional_integers: Vec<Option<i8>> = vec![None];

        for i in 1..(range + 1) {
            optional_integers.push(Some(i));
        }

        let mut cursor = range;

        // TODO: make this a while let statement - remember that vector.pop also
        // adds another layer of Option<T>. You can stack `Option<T>`s into
        // while let and if let.
        integer = optional_integers.pop() { 
        while let Some(Some(integer)) = optional_integers.pop() { 
            assert_eq!(integer, cursor);
            cursor -= 1;
        }

        assert_eq!(cursor, 0);
    }

参考资料

Powered by VitePress