MST

星途 面试题库

面试题:Rust函数的泛型与trait bounds深度应用

定义一个Rust函数,该函数是泛型函数,接收一个实现了`Clone`和`PartialOrd` trait的类型的集合(例如`Vec<T>`),函数要返回集合中的最大元素的克隆值。要求正确使用trait bounds,并处理集合为空时的情况。同时说明为什么要使用这些trait bounds,以及如果不满足这些bounds会出现什么编译错误。
39.9万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
fn find_max<T: Clone + PartialOrd>(collection: &[T]) -> Option<T> {
    if collection.is_empty() {
        None
    } else {
        let mut max = collection[0].clone();
        for item in collection.iter().skip(1) {
            if item > &max {
                max = item.clone();
            }
        }
        Some(max)
    }
}

使用这些trait bounds的原因

  1. Clone trait:因为函数需要返回集合中最大元素的克隆值,所以类型T必须实现Clone trait,这样才能克隆出最大元素并返回。
  2. PartialOrd trait:为了比较集合中的元素大小,类型T需要实现PartialOrd trait。PartialOrd trait提供了><等比较操作符的功能,使得我们可以判断哪个元素更大。

不满足这些bounds时的编译错误

  1. 未实现Clone trait:如果类型T没有实现Clone trait,在clone()调用处会出现编译错误,例如error[E0599]: no method named 'clone' found for type 'T' in the current scope
  2. 未实现PartialOrd trait:如果类型T没有实现PartialOrd trait,在比较if item > &max处会出现编译错误,例如error[E0369]: binary operation '>' cannot be applied to type 'T'