在 Rust 中使用子类型时如何避免代码重复?

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

我有这种配置来表示一个函数:

pub enum Function<T> {
    /// Euler's Number
    E,
    /// Pi
    PI,
    /// A Generic Number
    Num(f64),
    /// Natural Logarithm
    Basic {
        /// Type of the function
        kind: FunctionType,
        /// Argument of the function
        argument: Box<T>,
    },
    /// Composite function:
    Comp {
        /// Tuple with 2 pointers to other functions
        terms: (Box<T>, Box<T>),
        /// Opertor between the functions (+, -, /, *, ^, composition)
        operator: FunctionOperator,
    },
}

我还有一个将字符串解析为函数的函数。我现在想添加具有多维函数的能力,例如 Function1D、Function2D、Function3D,它们中的每一个都需要具有 get_derivative() 和 eval() 函数,但调用者的返回类型需要不同(的导数1D 函数是 1D 函数,但 3D 函数的导数是 3D 函数的 3D 向量)并且参数的数量也需要不同(即 1D 函数需要 1 f64 来评估函数,2D 函数需要 2 f64 .. .)

我试过像这样定义这个枚举但是代码不可能写

pub enum F1D {
    X,
    Function(Function<Self>),
}
pub enum F2D {
    X,
    Y,
    Function(Function<Self>),
}
pub enum F3D {
    X,
    Y,
    Z,
    Function(Function<Self>),
}
math inheritance rust polymorphism math-functions
© www.soinside.com 2019 - 2024. All rights reserved.