在生锈中如何在一行中进行此类型转换

时间:2014-11-01 23:34:49

标签: rust

我正在尝试使用位移,但我需要将结果作为f64。我似乎无法想象如何移动并将结果作为f64而不会使丑陋的tmp变化。

let num_bits: uint = 32; // just for reference

// how can these two lines be 1 line
let muli: int = 1<<(num_bits-2);
let mul: f64 = muli as f64;

如何将最后两行写成一行,以便我不需要muli

我尝试过以下主题的各种尝试:

 let m: f64 = 1<<(num_bits-2) as f64;

给出了playpen

  <anon>:8:21: 8:40 error: mismatched types: expected `uint`, found `f64` (expected uint, found f64)
  <anon>:8     let m: f64 = 1<<(num_bits-2) as f64;

2 个答案:

答案 0 :(得分:4)

您可以通过注释1文字的类型来实现。我假设您希望将转换结果设为int(在转换为f64之前),因为您说multi: int。否则,您需要1u

let m: f64 = (1i << (num_bits - 2)) as f64;

检查playpen

答案 1 :(得分:3)

如果查看生锈参考,您可以看到as运算符的优先级高于<<,因此您必须这样做:

fn main () {
    let num_bits: uint = 32; // just for reference
    let m: f64 = (1u << num_bits - 2) as f64;
    println!("mul {}", mul);
}

您还必须将1的副本指定为uint1u),因为编译器无法在以这种方式写入时从上下文中删除它的类型。