我刚开始摆弄 Rust,我发现了一个我不明白的错误,试图构建类似 DSL 的东西。
我定义了这样一个结构:
struct Thing<T> {
a: T
}
impl<T: Show> Thing<T> {
fn selfie<T>(&self) -> Thing<T> { Thing { a: self.a } }
fn say<T>(&self) { println!("sing") }
}
然后我这样调用它并得到错误:
let a = Thing { a: 1i }; // works
a.say(); // works
let s = a.selfie(); //works
s.say(); // error
main.rs:49:5: 49:12 error: cannot determine a type for this bounded type parameter: unconstrained type
main.rs:49 s.say();
^~~~~~~
有谁知道这个错误是什么意思?我很难弄明白,并且尝试了几种不同的类型转换,但似乎没有任何效果。
或者,是否有更好的方法来返回对“self”的引用(这是我真正想在“selfie”方法中做的,但由于引用生命周期而出现错误)或“等效结构”同类”?
最佳答案
这是用最新的 Rust 版本编译的。
use std::fmt::Show;
struct Thing<T> {
a: T
}
impl<T: Show + Clone> Thing<T> {
fn selfie(&self) -> Thing<T> { Thing { a: self.a.clone() } }
fn say(&self) { println!("sing: {}", self.a) }
}
我假设 say
方法实际上应该打印 a
(否则 Show 边界没有意义)。
问题是在say<T>
通用类型 T 存在但无法推断,因为它未被使用。在自拍方法中,<T>
不需要。如果我们想要克隆它,我们确实需要将 T 限制为实现 Clone 的那些类型。
我还应该指出 selfie
方法正在 reshape clone
.你可以这样做:
#[deriving(Clone)]
struct Thing<T> {
a: T
}
然后调用clone()
而不是 selfie
.
关于compiler-errors - 使用rust "cannot determine a type for this bounded type parameter: unconstrained type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25216964/