【问题标题】:Rust: "the type of this value must be known in this context" error for Float::piRust:Float::pi 的“此值的类型必须在此上下文中已知”错误
【发布时间】:2014-12-28 13:38:47
【问题描述】:

我有以下代码行,我希望它可以正常工作:

const pi_n4th_root : f32 = Float::pi().powf(-1.0/4.0);

但它会产生以下错误:

f.rs:7:28: 7:54 error: the type of this value must be known in this context
f.rs:7 const pi_n4th_root : f32 = Float::pi().powf(-1.0/4.0);
                                  ^~~~~~~~~~~~~~~~~~~~~~~~~~

我尝试添加所有可以添加的类型注释:

const pi_n4th_root : f32 = (Float::pi() as f32).powf(-1.0/4.0 as f32) as f32;

但它仍然失败并出现同样的错误:

f.rs:7:30: 9:55 error: the type of this value must be known in this context
f.rs:7 const pi_m4th_root : f32 = (Float::pi::<f32>() as f32).powf(-1.0/4.0 as f32) as f32;
                                   ^~~~~~~~~~~~~~~~~~~~~~~~~

似乎我需要以某种方式指定为 f32 类型调用 Float::pi,但该怎么做?

【问题讨论】:

    标签: rust type-inference


    【解决方案1】:

    很遗憾,您想做的事情不会有两个原因。

    首先,你不能这样写:

    const pi_n4th_root : f32 = Float::pi().powf(-1.0/4.0);
    

    也就是说,你不能在常量定义中调用任何函数,因为编译器应该知道常量的确切值,而 Rust 还没有编译时函数求值。

    其次,由于 UFCS 是 not yet implemented,因此您不能直接为某些特定类型调用 trait 方法。我不确定为什么 Float::pi() as f32 不起作用,但您也不能在路径中指定所需的类型。唯一的方法是编写一个单独的函数:

    #[inline]
    pub fn pi<T: Float>() -> T { Float::pi() }
    

    Rust 标准库中有很多这样的函数。然而,对于 Pi 常量,有一个更好的方法 - 您可以直接使用适当类型的常量:

    use std::f32;
    
    let pi = f32::consts::PI;
    

    你可以找到一个常量列表herehere(如果页面本身是空的,你可以按[src]链接,似乎是Rustdoc中的一个错误)。

    【讨论】:

    • 这些常量在core::f64::consts的文档页面上是可见的(doc.rust-lang.org/core/f64/consts)。
    • @Levans,我认为这可能是 Rustdoc JS 中的一个错误或类似的东西,因为当我按下 [src] 链接时,这些常量会在源页面打开之前暂时可见。无论如何,感谢您的链接。
    • 是的,文档首先将您重定向到 core::f64::consts,然后再打印源代码。
    • 哇,没注意到。很高兴知道)
    • 即使在非编译时也不起作用。我仍然得到这个“错误:这个值的类型必须在这个上下文中是已知的”。如何调用 Float::pi()?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多