为什么 Rust 在“impl"之后需要泛型类型声明?关键词? [英] Why does Rust require generic type declarations after the "impl" keyword?

查看:56
本文介绍了为什么 Rust 在“impl"之后需要泛型类型声明?关键词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义泛型的方法需要在impl后添加泛型:

Defining the methods of generic type requires adding generic types after impl:

struct GenericVal<T>(T,);
impl <T> GenericVal<T> {}

我觉得删除 似乎没问题:

I feel that removing <T> seems OK:

struct GenericVal<T>(T,);
impl GenericVal<T> {}

有什么特别的考虑吗?

推荐答案

Rust 允许您编写仅适用于某些特定类型参数组合的 impl 块.例如:

Rust allows you to write impl blocks that apply only to some specific combination of type parameters. For example:

struct GenericVal<T>(T);

impl GenericVal<u32> {
    fn foo(&self) {
        // method foo() is only defined when T = u32
    }
}

这里,类型 GenericVal 是通用的,但 impl 本身不是.

Here, the type GenericVal is generic, but the impl itself is not.

因此,如果您想编写一个适用于所有 GenericVal<T> 类型的 impl 块,您必须首先声明一个类型impl 本身的参数(否则,T 会尝试查找名为 T 的类型).

Thus, if you want to write an impl block that applies for all GenericVal<T> types, you must first declare a type parameter on the impl itself (otherwise, T would try to look up a type named T).

struct GenericVal<T>(T);

impl<T> GenericVal<T> {
    fn foo(&self) {
        // method foo() is always present
    }
}

此声明还允许您拥有一个可以多次使用的类型参数,从而强制类型相同.

This declaration also lets you have a single type parameter that can be used multiple times, forcing the types to be the same.

struct GenericVal<T, U>(T, U);

impl<V> GenericVal<V, V> {
    fn foo(&self) {
        // method foo() is only defined when T = U
    }
}

这篇关于为什么 Rust 在“impl"之后需要泛型类型声明?关键词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆