【问题标题】:E0277 "Sized is not implemented for the type [u8]", but my type does not have a [u8]E0277 “没有为类型 [u8] 实现大小”,但我的类型没有 [u8]
【发布时间】:2016-05-19 16:35:21
【问题描述】:

我正在制作 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 }
    }
}

当我编译这个时,我得到以下错误:

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

我搜索了这个错误,但它似乎指的是Sized没有实现的类型。奇怪的是,错误输出显示[u8] 没有实现Sized,但我的代码中甚至没有u8。会是什么?

【问题讨论】:

  • 样式点:空的new 可以通过实现Default trait 的default 方法更好地表达。它还使您的类型可以默认构造。

标签: rust


【解决方案1】:

问题是您的NodeType 枚举在其Include 变体中包含std::path::Path,但Path 是未调整大小的类型(因为它间接包含[u8],并且[u8] 未调整大小,因此你得到的错误)。

要解决此问题,请将Include 变体更改为包含&Path(如果节点应该借用路径)或PathBuf(如果节点应该拥有路径),或者更改Node::new()返回Box<Node>

Include 更改为包含&Path 需要将生命周期参数添加到NodeNodeType。当枚举不是Include 时,具体的生命周期可能是静态的。

下面的代码演示了它是如何工作的。注意Node 有两个 impl 块:第一个 (impl Node<'static>) 应该包含所有不使用生命周期参数的方法,而第二个 (impl<'a> Node<'a>) 应该包含所有使用的方法使用生命周期参数(包括所有带有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) }
    }
}

【讨论】:

  • 如果我将 Path 变成对 Path (&Path) 的引用,编译器会要求我终生使用。
  • 除了使用'static 作为生命周期之外,我什么都懂。它有什么作用?
  • 'static 表示该引用对象在整个程序的生命周期内都可用。但是,在Node::new() 中,我返回的枚举实际上并不存储引用,因此由于您无法从该枚举中获取引用,因此任何生命周期都是有效的。现在,我刚刚进行了测试,我认为将new() 放在通用impl 块中会引发一个错误,即编译器无法推断'a 的生命周期,但这不是真的(如果它是真的不过,它是一个类型参数)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 2023-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多