compiler-errors - 使用rust "cannot determine a type for this bounded type parameter: unconstrained type"

标签 compiler-errors rust

我刚开始摆弄 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/

相关文章:

c++ - 使用额外括号时为 "error: expected expression"

.net - Visual Studio : Compiler Warnings and errors appear twice in different languages

macos - 如何将 Rust 应用程序从 macOS x86 交叉编译到 macOS Silicon?

berkeley-db - 将 Rust 与 Berkeley DB 连接起来

java - 在注释中使用不可映射的字符构建项目?

compiler-errors - WiX 中的 & 注册表值

compiler-errors - VHDL:无法读取输出状态

rust - 如何在 Rust 中将字符串更改为数组

types - 函数的 Rust HashMap 的类型签名

rust - Rust 如何限制借用值的范围?