考虑一些不可访问但实现了API trait的结构体(HiddenInaccessibleStruct)。获得此隐藏类型的唯一方法是调用函数,该函数返回此类型的不透明实现。另一个结构体拥有某种类型,该类型使用此API trait。目前似乎无法在fn new()中分配此字段。以下代码也可以在Rust playgrounds找到:playgrounds。
// -- public api
trait Bound {
fn call(&self) -> Self;
}
// this is not visible
#[derive(Default)]
struct HiddenInaccessibleStruct;
impl Bound for HiddenInaccessibleStruct {
fn call(&self) -> Self { }
}
// -- public api
pub fn load() -> impl Bound {
HiddenInaccessibleStruct::default()
}
struct Abc<T> where T : Bound {
field : T
}
impl<T> Abc<T> where T : Bound {
pub fn new() -> Self {
let field = load();
Abc {
field // this won't work, since `field` has an opaque type.
}
}
}
更新 API特质Bound声明了一个返回Self的函数,因此它不是Sized。