我有以下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),
}

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

推荐答案

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

所以要么使用 struct 变体:

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

或单独的 struct :

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对象.

两者都会立即将您的 comments 转换为无法不同步的代码.作为额外的好处,您可以自由地重新编写创建实例的字段,并且PSP可以轻松为您提供帮助.

Rust相关问答推荐

在Rust中创建可变片段的可变片段的最有效方法是什么?

trait声明中的生命周期参数

这种获取-释放关系是如何运作的?

关于如何初始化弱 struct 字段的语法问题

字段类型为Boxed的 struct 的生存期必须超过static

你能在Rust中弃用一个属性吗?

`actix-web` 使用提供的 `tokio` 运行时有何用途?

处理带有panic 的 Err 时,匹配臂具有不兼容的类型

这个不安全的 Rust 代码有什么问题,所以它可以在 Windows 上运行,但不能在 Ubuntu 上运行?

Rust Axum 框架 - 解包安全吗?

需要一个有序向量来进行 struct 初始化

当没有实际结果时,如何在 Rust 中强制执行错误处理?

面临意外的未对齐指针取消引用:地址必须是 0x8 的倍数,但为 0x__错误

在1.5n次比较中找到整数向量中的最大和次大整数

当在lambda中通过引用传递时,为什么会出现终身/类型不匹配错误?

如何解析 Rust 中的 yaml 条件字段?

从 Cranelift 发出 ASM

Rust 中的通用 From 实现

返回 &str 但不是 String 时,borrow 时间比预期长

Rust:为什么在 struct 中borrow 引用会borrow 整个 struct?