rust - 如何将标记添加到具体类型?

标签 rust

我目前正在探索 Rust,但被以下问题难住了:

假设我想用 MarkerTrait “注释”一个函数参数(即使特征成为对的注释):

use std::marker::MarkerTrait;

pub trait X: MarkerTrait { }

pub trait MyInterface {
    fn foo(&self, bar: u32+ X) -> u32;
}

// make this compile in the playpen
fn main() { }

截至目前,编译器将拒绝此消息:消息:

<anon>:6:25: 6:28 error: expected a reference to a trait [E0172]
<anon>:6     fn foo(&self, bar : u32 + X) -> u32;
                                 ^~~

这是错误还是故意的?如果是故意的,我应该使用什么变通方法将所需信息添加到我的代码中?是否有其他方法来注释函数参数,例如 Lint 可以捡起来吗?

编辑:好的,看来我问错了问题。在java中,函数参数可以被注解。我如何在 Rust 中做类似的事情?

最佳答案

Rust 确实有注释,它们可以应用于 structfnmod 之类的项目:

#[test]
fn what() {}

但是,如果您使用自己的:

#[my_attr]
fn what() {}

你得到一个错误:

error: The attribute `my_attr` is currently unknown to the the compiler and may have meaning added to it in the future
help: add #![feature(custom_attribute)] to the crate attributes to enable

您也不能向参数添加注释:

fn what(#[my_attr] a: u8) {}

有错误

error: unexpected token: `#`

综上所述,我同意 Levans' sentiment - 使用类型来编码信息。

我所知道的 Java 中最常见的参数注释是 @Nullable。在 Rust 中,这有标准库支持,不依赖于外部元数据。您使用特殊类型来指示值可以不存在 - Option:

fn what(a: Option<u8>) {}

您还可以构建自己的类型来指示语义。也许您有处理距离的应用程序?创建一个代表它的类型:

struct Meters(i32);

关于rust - 如何将标记添加到具体类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28812052/

相关文章:

rust - 为迭代其 HashMap 属性的结构实现 IntoIterator

linux - 使用 Rust 显示文件元数据,如所有者和组

string - Vec::dedup 不起作用——我如何对字符串向量进行重复数据删除?

rust - 如何将 `impl Clone for` 设为不允许移动的类型?

rust - cargo 条件依赖功能

rust - 在 Optional 中展开结果

c - 将 Rust 指针传递给 C 时,我应该得到 0x1 吗?

rust - 在其他模块中包含 main.rs

rust - 在调用时引用其自身字段之一的结构上设置处理程序

rust - while 循环中变量的突变