Rust 数据类型的转换

Rust 提供了多种类型转换的方式。

1. as T

用于数类型之间的转换。ixx, uxx, fxx 都可以。 注意:当溢出的时候,转换不会 panic,而是循环映射值。

fn as_type() {
    // i32 -> i8
    println!("{}", 127i32 as i8);
    // output: 127
    println!("{}", 128i32 as i8);
    // output: -128

    // f64 -> i32 (floor)
    println!("{}", -10000.678f64 as i32);
    // output: -10000

    // integer divide
    for i in 1..10 {
        print!("{} ", i / 2);
    }
    // output: 0 1 1 2 2 3 3 4 4
    println!();

    // float divide
    for i in 1..10 {
        print!("{} ", i as f64 / 2.0);
    }
    // output: 0.5 1 1.5 2 2.5 3 3.5 4 4.5
    println!();
}

2. TryFrom/TryInto

可以在不同的数类型之间转换,越界时,会返回错误。 TryFrom/TryInto 的结果是 Result<T, Error>

use std::convert::TryFrom;
use std::convert::TryInto;

fn try_from_try_into() {
    println!("{}", i8::try_from(32i32).unwrap());
    // output: 32, panic if the value is not fit to i8.
    let i_8: i8 = 32i32.try_into().unwrap();
    println!("{}", i_8);
    // output: 32, panic if the value is not fit to i8.
}

3. From/Into 

只能从小范围数类型变成大的数类型。安全。 也可以用于 str 和 String 之间的转换。

use std::convert::From;
use std::convert::Into;

fn from_into() {
    println!("{}", i32::from(127i8));
    // output: 127
    let i_32: i32 = 127i8.into();
    println!("{}", i_32);
    // output: 127
}

4. unsafe

// Cargo.toml
// [dependencies]
// rand = "0.8.3"
use rand::random;

fn unsafe_f64() {
    println!("{}", unsafe {
        f64::to_int_unchecked::(random::() * 100.0)
    });
    // output: 67
}

5. to_string/parse

用于字符串和数类型之间转换

fn to_string_parse() {
    // string -> float
    let s = "123.456";
    println!("{} ", s.parse::().unwrap());
    // output: 123.456

    // float -> string
    let f_64 = 123.456;
    println!("{} ", f_64.to_string());
    // output: 123.456

    // float -> string
    let f_64 = 123.456;
    println!("{} ", f_64.to_string());
    // output: 123.456
}

6. 在日期和字符串之间转换

// Cargo.toml
// [dependencies]
// chrono = "0.4"
use chrono::*;

fn date_time() {
    let locale = Local.ymd(2020, 12, 05).and_hms(12, 0, 9);
    println!("{:?}", locale.format("%Y-%m-%d %H:%M:%S.%s").to_string());
    // "2020-12-05 12:00:09.1607140809"

    println!("{:?}", locale.format("%a %b %e %T %Y").to_string());
    // "Sat Dec  5 12:00:09 2020"

    println!("{:?}", locale.format("%c").to_string());
    // "Sat Dec  5 12:00:09 2020"

    println!("{:?}", locale.to_string());
    // "2020-12-05 12:00:09 +08:00"

    println!("{:?}", locale.to_rfc2822());
    // "Sat, 05 Dec 2020 12:00:09 +0800"

    println!("{:?}", locale.to_rfc3339());
    // "2020-12-05T12:00:09+08:00"

    let date_str = "2020-04-12 22:10:57";
    let naive_datetime = NaiveDateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S").unwrap();
    println!("{:?}", naive_datetime.to_string());
    // "2020-04-12 22:10:57"

    let date_str = "2020-04-12 22:10:57 +02:00";
    let datetime = DateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S %z").unwrap();
    println!("{:?}", datetime.to_string());
    // "2020-04-12 22:10:57 +02:00"

    let date_str = "2020-04-12";
    let naive_date = NaiveDate::parse_from_str(date_str, "%Y-%m-%d").unwrap();
    println!("{:?}", naive_date.to_string());
    // "2020-04-12"

    let time_str = "22:10:57";
    let naive_time = NaiveTime::parse_from_str(time_str, "%H:%M:%S").unwrap();
    println!("{:?}", naive_time.to_string());
    // "22:10:57"
}

下一章:Rust 字符串拼接

Rust 有两类字符串,`String` 类型基于向量列表 `Vec<u8>`,另一类字符串是 `&str` 它是切片类型 `&[u8]`。C++ 程序拼接字符串:string s1 = " ...