Rust 学习笔记:关于高级 trait 的练习题
Rust 学习笔记:关于高级 trait 的练习题
参考视频:
- https://www.bilibili.com/video/BV14b5Xz5E5f
问题一
Add trait 的定义:
trait Add<Rhs=Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}
以下哪一项最能解释为什么 Output 是一个关联类型,而 Rhs 是一个类型参数?
A. 一个 trait 只能有一一个关联类型,所以 Rhs 必须是 Add 的类型参数
B. 一个类型 T 应该可以与许多其他类型 S 相加,但给定的 T+S 操作应该总是有一个确定的输出类型
C. 关联类型不能有默认值,而 trait 类型参数可以有默认值
D. add 操作以 Rhs 为输入,输出为 Output,而类型参数用于输入,关联
类型用于输出
答:B。
问题二
Add trait 的定义:
trait Add<Rhs=Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}
以下哪一项最能解释为什么 Rhs 是 Add trait 的一个类型参数,而不是 add 函数的类型参数?也就是说,为什么 Add 没有被设计成下面这样:
trait Add {
type Output;
fn add<Rhs>(self, rhs: Rhs) -> Self::Output;
}
A. 当 Rhs 是 trait 级别的类型参数时,类型检查器的执行效率更高
B. Rhs 作为函数级别的类型参数时,无法拥有默认类型
C. 因为函数级别的类型参数会导致 add 函数在代码生成时需要额外的单态化时间
D. 如果 Rhs 是函数级别的类型参数,那么 add 的定义将无法假设 Rhs 的任何结构
答:D。
问题三
以下代码能否通过编译?若能,输出是?
mod inner {
pub trait A {
fn f(&self) -> usize { 0 }
}
pub trait B {
fn f(&self) -> usize { 1 }
}
pub struct P;
impl A for P {}
impl B for P {}
}
fn main() {
use inner::{P, B};
println!("{}", P.f());
}
答:可以通过编译。输出 1。
问题四
考虑为某个类型 T 实现一个名为 Trait 的 trait。在下列哪种情况下,你需要使用 newtype 模式(即用一个新类型包裹 T)?
A. Trait 定义于本地 crate,T 也定义于本地 crate
B. Trait 定义于外部 crate,T 定义于本地 crate
C. Trait 定义于本地 crate,T 定义于外部 crate
D. Trait 定义于外部 crate,T 也定义于外部 crate
答:D。