"too many parameters" 完美功能

"too many parameters" on perfectly fine function

我有类似的代码:

pub trait WorldImpl {
    fn new(size: (usize, usize), seed: u32) -> World;
    fn three() -> bool;
    fn other() -> bool;
    fn non_self_methods() -> bool;
}
pub type World = Vec<Vec<UnitOfSpace>>;
// I'm doing this because I want a SPECIAL version of Vec<Vec<UnitOfSpace>>, so I can treat it like a struct but have it be a normal type underneath.
impl WorldImpl for World {
    fn new(size: (usize, usize), seed: u32) -> World {
    // Code
        vec![/* vector stuff */]
    }
    // Implement other three methods
}
let w = World::new((120, 120), /* seed from UNIX_EPOCH stuff */);

我得到这个错误,这显然是错误的:

error[E0061]: this function takes 0 parameters but 2 parameters were supplied
  --> src/main.rs:28:28
   |
28 |     let world = World::new((120 as usize, 120 as usize),
   |                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected 0 parameters

我在想两件事:

  1. 这不是惯用的,Rust 从来没有打算以这种方式使用。在这种情况下,我需要知道如何真正做到这一点。

  2. 我遗漏了一个愚蠢的错误。

当我在 playground 上尝试与上面类似的代码时,它工作正常,没有错误。我在其他任何地方都没有找到任何关于此类错误的信息,所以如果我发现我只是使用了错误的语言,我不会感到惊讶。我对我的任何代码都没有特别的依恋,所以请告诉我这个成语是什么!

您的类型 WorldVec<Vec<UnitOfSpace>> 的别名。 Vec<T> 提供了一个名为 new 的固有关联函数,它不带参数。编译器更喜欢选择固有关联函数而不是 traits 中定义的关联函数,因此它选择不带参数的固有 new 而不是你自己的 new 有 2 个参数。

这里有几个选项可以解决这个问题:

  1. 显式调用特征的关联函数:

    let w = <World as WorldImpl>::new((120, 120), /* seed from UNIX_EPOCH stuff */);
    
  2. 使World成为一个新类型(struct World(Vec<Vec<UnitOfSpace>>);),这样你就可以定义固有的关联函数(但是Vec的固有方法将不会World).

  3. WorldImpl::new 重命名为 Vec 上的固有关联函数未使用的名称。

您尝试做的事情没有多大意义。您已将 World 设为 Vec<Vec<UnitOfSpace>> 的类型别名,因此它们完全可以互换 - 您为一个添加的实现将应用于另一个,反之亦然。

如果您想以不同的方式对待这种类型,请将其包装在新类型中:

struct World(Vec<Vec<UnitOfSpace>>);

现在这是不同于 Vec<Vec<UnitOfSpace>> 的类型,但运行时开销为零。

您的实际错误是因为您在 World 中添加了一个名为 new 的方法作为 WorldImpl 实现的一部分,但 WorldVec 已经有一个 new 方法(参数为零!)。