如何在不传递变量或使用全局变量的情况下使变量可用于函数,还是应该采用不同的方法?

我正在编写一个函数来修复 Rust(以及其他语言)中的浮点精度问题。我需要根据传递的参数选择函数.floor().ceil()函数内。解决此问题的最佳方法是什么。如果功能以外的东西更好地服务于建议,无论如何!感谢您的帮助!

fn main() {
    to_round(7.987, "floor");
}

fn to_round(n: f64, floor_or_ceil: &str) -> f64 {
    fn test(diff_n: f64) -> f64 {
        if floor_or_ceil == "floor" {
           diff_n.floor()
        } else {
           diff_n.ceil()
        }
    }
    test(n)
}

回答

如果您用闭包替换您的内部fn函数,那么您拥有的代码将被编译。闭包可以引用封闭范围内的变量,而s 不能。fn

fn main() {
    to_round(7.987, "floor");
}

fn to_round(n: f64, floor_or_ceil: &str) -> f64 {
    let test = |diff_n: f64| -> f64 {
        if floor_or_ceil == "floor" {
           diff_n.floor()
        } else {
           diff_n.ceil()
        }
    };
    test(n)
}

但是,关闭确实有一些警告;特别是,它们不能是泛型函数,并且不能在函数指针可以存在的地方使用(除非它们没有提到(“关闭”)封闭作用域中的任何变量,并且仅使用闭包语法而不是fn语法) )。

此类问题最通用的干净解决方案是显式传递所需的参数,您可以通过使用结构(尤其是需要多个值时)和使函数该结构的方法:

fn main() {
    let c = MathContext { rounding_mode: "floor" };

    c.to_round(7.987);
}

struct MathContext {
    rounding_mode: &'static str,  // Side note: this should really be an enum, not a string

    // And you can add more fields here for any other parameters needed.
}

impl MathContext {
    fn to_round(&self, n: f64) -> f64 {
        self.test(n)
    }

    fn test(&self, diff_n: f64) -> f64 {
        if self.rounding_mode == "floor" {
           diff_n.floor()
        } else {
           diff_n.ceil()
        }
    }
}

这组方法是否适合取决于您实际在做什么;如果test非常具体,to_round那么以这种方式将其拉出是没有意义的。但这种模式似乎可能在您的代码中的其他地方有用,至少,如果您正在做诸如选择哪种方式来舍入数字之类的事情。


以上是如何在不传递变量或使用全局变量的情况下使变量可用于函数,还是应该采用不同的方法?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>