MST
星途 面试题库

面试题:Rust特征约束泛型在trait关联类型中的深度应用

定义一个特征`trait MyTrait`,它有一个关联类型`AssociatedType`,这个关联类型需要满足`std::fmt::Display`和`std::cmp::PartialOrd`特征约束。然后定义一个结构体`MyStruct`,它实现`MyTrait`,在实现中确定`AssociatedType`的具体类型。接着编写一个函数`compare_and_display`,该函数接受一个实现了`MyTrait`的类型的实例,比较并显示该实例的`AssociatedType`类型的值。请完整实现上述特征、结构体和函数。
45.0万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
trait MyTrait {
    type AssociatedType: std::fmt::Display + std::cmp::PartialOrd;
}

struct MyStruct {
    value: i32,
}

impl MyTrait for MyStruct {
    type AssociatedType = i32;
}

fn compare_and_display<T: MyTrait>(instance: T) {
    let value1 = instance.value;
    let value2 = 42;

    if value1 < value2 {
        println!("{} is less than {}", value1, value2);
    } else if value1 > value2 {
        println!("{} is greater than {}", value1, value2);
    } else {
        println!("{} is equal to {}", value1, value2);
    }
}