如何记录Rust函数的参数?

50
rustdoc允许您通过在每行上方包含文档注释来记录结构字段和枚举变体。
enum Choices {
  /// The first choice.
  First,
  /// The second choice.
  Second,
}

struct Person {
  /// The person's name.
  name: String,
  /// The person's age.
  age: u8,
}

这些将在由rustdoc生成的HTML中以漂亮的格式显示出来。然而,我还没有看到任何制作类似漂亮格式的函数参数文档的方法。是否有一种“官方”的方式来对它们进行文档化,还是只能在函数的主要文档部分中自由描述它们?

就我个人而言,我更喜欢利用类型系统。不要说“这个u8必须是2的幂或质数”,而是创建一个名为PowerOfTwoOrPrime的新类型,并使用适当的构造函数。 - Shepmaster
1
目前没有针对此的语法规定,也没有相关的指导或约定。 - bluss
3个回答

47

我看过一些示例中使用了以下样式:

/// Brief.
///
/// Description.
/// 
/// * `foo` - Text about foo.
/// * `bar` - Text about bar.
fn function (foo: i32, bar: &str) {}

对我来说,到目前为止它也很好用。

P.S. 这个问题也有一个issue
P.S. 还要检查改进的rustdoc 链接搜索别名 在1.48中
P.S. 现在有一个文档在https://doc.rust-lang.org/beta/rust-by-example/meta/doc.html


有点像JSDoc。我认为它更符合人体工程学。您可以一眼看到完整的函数文档。 - Paul-Sebastian Manole
更新了 P.S. 链接到问题。 - Bryan Larsen
只想指出其他官方参考资料:https://doc.rust-lang.org/beta/rust-by-example/meta/doc.html - Rahmat Nazali Salimi

29

根据 Rust 文档,函数文档的格式如下:

#![crate_name = "doc"]

/// A human being is represented here
pub struct Person {
    /// A person must have a name, no matter how much Juliet may hate it
    name: String,
}

impl Person {
    /// Returns a person with the name given them
    ///
    /// # Arguments
    ///
    /// * `name` - A string slice that holds the name of the person
    ///
    /// # Examples
    ///
    /// ```
    /// // You can have rust code between fences inside the comments
    /// // If you pass --test to `rustdoc`, it will even test it for you!
    /// use doc::Person;
    /// let person = Person::new("name");
    /// ```
    pub fn new(name: &str) -> Person {
        Person {
            name: name.to_string(),
        }
    }

    /// Gives a friendly hello!
    ///
    /// Says "Hello, [name]" to the `Person` it is called on.
    pub fn hello(& self) {
        println!("Hello, {}!", self.name);
    }
}

fn main() {
    let john = Person::new("John");

    john.hello();
}


22

有没有官方的方式来记录它们?

目前没有官方的方式来记录参数。


2
由于这个答案已经三年了,我想询问一下是否有任何关于此事的更新 - 至少我没有找到任何信息。 - Philipp Ludwig
6
没有这样的需求。大多数人依赖于类型和参数名称,通常很清晰明了。如果需要澄清,大多数人使用一些散文,而不是rustdoc需要理解的东西。 - Steve Klabnik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接