我将类型定义为固定大小的数组,并尝试为其实现一些自定义方法。
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
用于struct
或enum
。您的情况的快速解决方法是将 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/