官术网_书友最值得收藏!

  • Learning Rust
  • Paul Johnson Vesa Kaihlavirta
  • 215字
  • 2021-07-02 23:07:17

Casting

Rust allows for variables to be cast differently. This is achieved using the as keyword. This works in the same way as it does in C#:

let my_score = 10i32; 
let mut final_score : u32 = 100; 
let final_score = my_score as u32; 

We can also cast to a different type (for example, float to int):

let pi = 3.14; 
let new_pi = pi as i32; // new_pi = 3 

However, the effects of precision-losing casts like this one may not be desirable. For instance, if you cast a float that's over the bit size of i8 to i8, the number gets truncated to 0:

let n = 240.51; 
let n_as_int = n as i8; // n_as_int = 0   

An error will occur if the types you are attempting to cast to are not compatible; for example:

let my_home = "Newton-le-Willows"; 
let my_number = my_home as u32; // cannot convert &str to u32 

Rust does not do implicit casting between primitive types, even when it would be safe. That is, if a function expects an i8 as a parameter, you must cast an i16 value to i8 before passing it. The reason for this is to achieve the maximum type checking and, therefore, reduce the number of potential (and more problematic) hidden bugs.

主站蜘蛛池模板: 阜平县| 葫芦岛市| 仲巴县| 临夏市| 沾益县| 修武县| 精河县| 孟连| 万年县| 克山县| 石屏县| 富蕴县| 炎陵县| 大兴区| 永丰县| 出国| 仙游县| 兰西县| 宾川县| 新建县| 连南| 怀安县| 宁阳县| 绥阳县| 桃园市| 西乌| 保定市| 应用必备| 乌拉特中旗| 佛冈县| 金沙县| 岚皋县| 来凤县| 大英县| 汉中市| 陇川县| 冷水江市| 鄂州市| 乌拉特前旗| 曲周县| 潞西市|