我有一些代码可以正常类型,但当我添加泛型它会引发错误.
它给我以下错误,我的代码如下:
该特征
core::fmt::Display未针对T[E0277] 类型实施
fn own<T>(x: T) -> T
{
x
}
struct Node<T>
{
value: T,
next: Option<Box<Node<T>>>
}
impl<T> Node<T>
{
fn print(&self)
{
let mut current = self;
loop {
println!("{}", current.value);
match current.next {
Some(ref next) => { current = &**next; },
None => break,
}
}
}
fn add(&mut self, node: Node<T>)
{
let item = Some(Box::new(node));
let mut current = self;
loop {
match own(current).next {
ref mut slot @ None => { *slot = item; return },
Some(ref mut next) => current = next
}
}
}
}
fn main() {
let leaf = Node { value: 10, next: None };
let branch = Node { value : 50, next: Some(Box::new(leaf)) };
let mut root = Node { value : 100, next: Some(Box::new(branch)) };
root.print();
let new_leaf = Node { value: 5, next: None };
root.add(new_leaf);
root.print();
}
Run Code Online (Sandbox Code Playgroud)
我理解这是所有语言中泛型的常见错误,但是当我尝试向泛型添加约束时,我得到另一个错误:
<anon>:12:8: 12:26 error: failed to resolve. Use of undeclared type or module core::fmt
<anon>:12 impl<T:core::fmt::Display> Node<T>
如果我从错误中复制了完整限定名并将其作为约束插入,为什么会出现?
例如,它也不适用于其他特征impl<T:Num>
这是Rust的一个丑陋的疣,我希望它能在某一天得到解决.短版本是您想要的std::fmt::Display,而不是core::fmt::Display:
impl<T> Node<T>
where
T: std::fmt::Display,
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
更长的答案是Rust标准库分为两部分:std和core.core是一个较低级别的图书馆(强调我的):
Rust Core Library是Rust标准库的无依赖基础.它是语言与其库之间的可移植粘合剂,定义了所有Rust代码的内在和原始构建块.它链接到没有上游库,没有系统库,也没有libc.
核心库是最小的:它甚至不知道堆分配,也不提供并发或I/O. 这些东西需要平台集成,这个库与平台无关.
不建议使用核心库.libcore的稳定功能从标准库中重新导出.该图书馆的构成可能会随着时间的推移而变化; 只有通过libstd公开的接口才是稳定的.
实现一次进入core和进入一次项目是愚蠢的std,因此标准库从其自身重新导出项目core.然而,从代码core知道本身core,而不是std,那么错误信息是指较低的水平.
| 归档时间: |
|
| 查看次数: |
1444 次 |
| 最近记录: |