我正在做一Node棵树.这是代码:
use std::option::Option;
use std::path;
#[derive(Debug)]
enum NodeType {
Binding((String, String)),
Header,
Include(path::Path),
Raw(String),
}
#[derive(Debug)]
pub struct Node {
node_type: NodeType,
}
impl Node {
fn new() -> Node {
Node { node_type: NodeType::Header }
}
}
Run Code Online (Sandbox Code Playgroud)
当我编译它时,我收到以下错误:
error[E0277]: the trait bound `[u8]: std::marker::Sized` is not satisfied in `std::path::Path`
--> src/main.rs:8:13
|
8 | Include(path::Path),
| ^^^^^^^^^^^ within `std::path::Path`, the trait `std::marker::Sized` is not implemented for `[u8]`
|
= note: `[u8]` does not have a constant size known at compile-time
= note: required because it appears within the type `std::path::Path`
= note: only the last field of a struct may have a dynamically sized type
Run Code Online (Sandbox Code Playgroud)
我搜索了这个错误,但似乎是指Sized未实现的类型.奇怪的是,错误输出说[u8]没有实现Sized,但u8在我的代码中甚至没有.会是什么呢?
问题是你的NodeType枚举std::path::Path在其Include变体中包含一个,但是Path是一个unsized类型(因为它包含一个[u8]间接的,并且[u8]是unsized,因此你得到的错误).
要解决此问题,请更改Include变量以包含a &Path(如果节点应借用路径)或a PathBuf(如果节点应拥有路径),或者更改Node::new()为return Box<Node>.
改变Include以包含&Path需要添加一个寿命参数Node和NodeType.当enum不是a时,具体的生命周期可能是静态的Include.
下面的代码演示了这将如何工作.注意有两个impl块Node:第一个(impl Node<'static>)应该包含所有不使用lifetime参数的方法,而第二个(impl<'a> Node<'a>)应该包含所有使用lifetime参数的方法(包括带self参数的所有方法)).
use std::path;
#[derive(Debug)]
enum NodeType<'a> {
Binding((String, String)),
Header,
Include(&'a path::Path),
Raw(String),
}
#[derive(Debug)]
pub struct Node<'a> {
node_type: NodeType<'a>,
}
impl Node<'static> {
fn new() -> Node<'static> {
Node { node_type: NodeType::Header }
}
}
impl<'a> Node<'a> {
fn include(path: &'a path::Path) -> Node<'a> {
Node { node_type: NodeType::Include(path) }
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2871 次 |
| 最近记录: |