如何在 Rust 中为具有多个数据持有者的枚举变体编写文档注释?

问题描述 投票:0回答:1

我有以下内容

enum

pub enum Force {
    Elastic(f64, f64),
    Damping(f64),
    Gravitational,
    Sticky(f64, f64, f64, f64),
}

我想记录每个变体的每个参数的含义。我一直在查找 Rust 书、Rustdoc 书等,但找不到关于此的特定部分。例如:

/// Represents a force.
pub enum Force {
    /// The force by an ideal spring, parameters are (k,d0).
    Elastic(f64, f64),
    /// The force by a linear damping, the parameter is the proportionality factor between velocity and force.
    Damping(f64),
    /// Gravitational force given by Newton's formula.
    Gravitational,
    /// A sticky force, parameters are (d_well, d_max, F_sticky, F_repuls).
    Sticky(f64, f64, f64, f64),
}

虽然达到了目的,但我想知道标准是什么

rust enums documentation
1个回答
2
投票

惯用的方法是使用描述性代码而不是元组变体的未命名字段。

所以要么使用结构变体:

pub enum Force {
    /// A sticky force
    Sticky {
        /// The distance at which the lowest potential is found.
        d_well: f64,
    },
}

或单独的结构:

pub enum Force {
    /// A sticky force
    Sticky(Sticky),
}
pub struct Sticky {
    /// The distance at which the lowest potential is found.
    pub d_well: f64,
}

后者的优点是您可以谈论

Sticky
及其字段,而不必谈论整个
Force
对象。

两者都会立即将您的评论变成不会不同步的代码。作为额外的好处,您可以自由地重新编码创建实例的字段,并且 LSP 可以轻松地为您提供帮助。

© www.soinside.com 2019 - 2024. All rights reserved.