Skip to content
On this page

Trait4: exercises/traits/traits4.rs

题目

rust
// traits4.rs
//
// Your task is to replace the '??' sections so the code compiles.
//
// Don't change any line other than the marked one.
//
// Execute `rustlings hint traits4` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

pub trait Licensed {
    fn licensing_info(&self) -> String {
        "some information".to_string()
    }
}

struct SomeSoftware {}

struct OtherSoftware {}

impl Licensed for SomeSoftware {}
impl Licensed for OtherSoftware {}

// YOU MAY ONLY CHANGE THE NEXT LINE
fn compare_license_types(software: ??, software_two: ??) -> bool {
    software.licensing_info() == software_two.licensing_info()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn compare_license_information() {
        let some_software = SomeSoftware {};
        let other_software = OtherSoftware {};

        assert!(compare_license_types(some_software, other_software));
    }

    #[test]
    fn compare_license_information_backwards() {
        let some_software = SomeSoftware {};
        let other_software = OtherSoftware {};

        assert!(compare_license_types(other_software, some_software));
    }
}

您的任务是替换??部分的代码,以便代码通过编译。

除了标记行以外,不要有任何的修改行为。

题目解析

在这个题目中,我们可以使用特征,而不使用具体的类型作为参数。

rust
fn compare_license_types(software: ??, software_two: ??) -> bool { 
fn compare_license_types(software: impl Licensed, software_two: impl Licensed) -> bool { 
    software.licensing_info() == software_two.licensing_info() 
} 

参考资料

Powered by VitePress