compiler-errors - 具有泛型编译错误的 Rust 结构

标签 compiler-errors rust

我用 Rust 编写了以下代码。版本为 0.12.0-pre-nightly。

struct Sample<T> {
    x: T
}

impl<T> Sample<T> {
    pub fn new<T>(v: T) -> Sample<T> {
        Sample { x: v }
    }

    pub fn get<T>(&self) -> T {
        self.x
    }
}

fn main() {
    Sample::new(0i).get(); // expect int 0
}

编译错误。

hoge.rs:11:9: 11:15 error: mismatched types: expected `T`, found `T` (expected type parameter, found type parameter)
hoge.rs:11         self.x

我无法通过编译器消息找出示例程序无法编译的原因。 我该如何解决?

最佳答案

不要将类型参数放在您的方法上。他们必须使用 impl 中的那个.

struct Sample<T> {
    x: T
}

impl<T> Sample<T> {
    pub fn new(v: T) -> Sample<T> {
        Sample { x: v }
    }

    pub fn get(&self) -> T {
        self.x
    }
}

fn main() {
    Sample::new(0i).get(); // expect int 0
}

P.S.:该代码也无法编译,因为 get试图移动x来自 &self .您可以更改 impl<T>impl<T: Copy>如果你只想使用可复制类型,或者更改 get返回引用:

    pub fn get(&self) -> &T {
        &self.x
    }

关于compiler-errors - 具有泛型编译错误的 Rust 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26071757/

相关文章:

c++ - 在 C++ 中写入文件的编译错误

generics - Rust 期望生成器有两个级别的装箱,而我只指定了一个

c++ - 调试 websocket++ broadcast_server.cpp ('owner_less' 不是 'std' 的成员)

Scala 使用 () 应用 PartialFunction 与 .apply() 不同

Scala:为什么我必须在这里加上额外的括号?

rust - std::sync::mpsc::channel 总是以相同的顺序

parsing - 无法为 filter_map().sum() 推断 `B` 的类型

rust - 匹配武器 : "mismatched types expected (), found integral variable"

closures - 如何从函数返回 Rust 闭包?

c++ - 为 x64 平台编译时出现 c2593 错误(运算符标识符不明确)