rust - "impl requires a base type"用于 Rust 中的类数组类型

标签 rust

我将类型定义为固定大小的数组,并尝试为其实现一些自定义方法。

type Vec3 = [f64; 3];

impl Vec3 {
    fn display(&self) {
        println!("x = {}, y = {}, z = {}", self[0], self[1], self[2]);
    }
}

我收到这个错误:

error[E0118]: no base type found for inherent implementation
 --> src/main.rs:7:6
  |
7 | impl Vec3 {
  |      ^^^^ impl requires a base type
  |
  = note: either implement a trait on it or create a newtype to wrap it instead

error: aborting due to previous error

此错误的性质是什么?我该如何修复我的代码?

最佳答案

你的线路

type Vec3 = [f64; 3];

并没有真正声明一个新类型,它只是声明了一个type alias。为数组 [f64; 调用了 Vec3; 3]

当我们运行 rustc --explain E0118 时,Rust 编译器会帮助我们描述它:

You're trying to write an inherent implementation for something which isn't a
struct nor an enum.

因此,您只能将impl 用于structenum。您的情况的快速解决方法是将 Vec3 声明为 tuple Struct :

struct Vec3([f64; 3]);

但这意味着要稍微重写您的 display 方法。为清楚起见,我们将解构为局部变量:

    let Self(vec) = self;
    println!("x = {}, y = {}, z = {}", vec[0], vec[1], vec[2]);

您可以在 Playground (43122f5fdbd157b9925a5fd2f660c329) 上看到一个工作示例.

关于rust - "impl requires a base type"用于 Rust 中的类数组类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58350023/

相关文章:

testing - 我如何在 Rust 中测试私有(private)方法?

rust - 选择动态创建的 channel

pattern-matching - 如何匹配具有常量值的结构中的字符串?

rust - 我可以确定泛型类型的零值吗?

rust - 为什么 rust 的 read_line 函数使用可变引用而不是返回值?

rust - 如何修改我的构造函数以接受切片或对数组或向量的引用

rust - Rust 匹配表达式类型是不确定的吗?

rust - Rust是否会缩小生命周期以满足对其定义的约束?

types - 以特定结构作为参数的特征实现

rust - 从循环内部向外部范围内的容器存储借来的值?