gpt4 book ai didi

RuSTLings Traits4.rs 为什么 impl Trait 语法有效,但特征绑定(bind)语法或 where 子句不起作用

转载 作者:行者123 更新时间:2023-12-03 08:03:05 25 4
gpt4 key购买 nike

我正在做 RuSTLings 类(class) Traits4.rs 练习。该任务基本上是为 compare_license_types 函数选择正确的签名。使用如下的 impl Trait 语法效果很好:

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

struct SomeSoftware {}

struct OtherSoftware {}

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

fn compare_license_types(software: impl Licensed, software_two: impl Licensed) -> 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));
}
}

如果我更改函数签名以使用特征绑定(bind)语法或 where 子句,它将不再编译:

fn compare_license_types<T: Licensed>(software: T, software_two: T) -> bool {}
// Or
fn compare_license_types<T>(software: T, software_two: T) -> bool
where T: Licensed {}

两者都因编译错误而失败:

error[E0308]: mismatched types
--> exercises/traits/traits4.rs:37:54
|
37 | assert!(compare_license_types(some_software, other_software));
| ^^^^^^^^^^^^^^ expected struct `SomeSoftware`, found struct `OtherSoftware`

error[E0308]: mismatched types
--> exercises/traits/traits4.rs:45:55
|
45 | assert!(compare_license_types(other_software, some_software));
| ^^^^^^^^^^^^^ expected struct `OtherSoftware`, found struct `SomeSoftware`

我在这里缺少什么?

最佳答案

fn compare_license_types<T: Licensed>(software: T, software_two: T) -> bool { ...

告诉编译器 softwaresoftware_two 都具有类型 T,其中 T 可以是实现的任何类型已获得许可。当您传入类型为 SomeSoftwaresome_software 时,Rust 会推断 T 类型必须是 SomeSoftware。但参数 software_two 也具有类型 T,即类型 SomeSoftware。但您要向其传递一个 OtherSoftware 类型的参数。这就是它无法编译的原因。

您可以通过使 compare_license_types 对两个都实现 Licensed 的不同类型通用来解决此问题:

fn compare_license_types<T: Licensed, U: Licensed>(software: T, software_two: U) -> bool { ...

这就是 impl Trait 语法隐式执行的操作。

关于RuSTLings Traits4.rs 为什么 impl Trait 语法有效,但特征绑定(bind)语法或 where 子句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73319281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com