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

时间:2015-03-02 14:20:32

标签: rust

我目前正在探索Rust,我对以下问题感到困惑:

我们想要#34;注释"带有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() { }

截至目前的编译器将使用以下内容拒绝此消息:message:

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

这是一个错误还是故意的?如果是故意的,我应该使用哪种解决方法将所需信息添加到我的代码中?是否有其他方法来注释函数参数,例如棉绒可以拿起来吗?

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

1 个答案:

答案 0 :(得分:1)

Rust确实有注释,可以应用于structfnmod s等项目:

#[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);