前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[Rust] 数据类型的转换

[Rust] 数据类型的转换

作者头像
绿巨人
发布2021-05-10 10:36:03
1.9K0
发布2021-05-10 10:36:03
举报

数据类型的转换

类型转换的方式

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

  • 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!();
}
  • 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.
}
  • From/Into 只能从小范围数类型变成大的数类型。安全。 也可以用于 strString 之间的转换。
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
}
  • unsafe
// Cargo.toml
// [dependencies]
// rand = "0.8.3"
use rand::random;

fn unsafe_f64() {
    println!("{}", unsafe {
        f64::to_int_unchecked::<usize>(random::<f64>() * 100.0)
    });
    // output: 67
}
  • to_string/parse

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

fn to_string_parse() {
    // string -> float
    let s = "123.456";
    println!("{} ", s.parse::<f64>().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
}

在日期和字符串之间转换

// 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"
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-05-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 数据类型的转换
    • 类型转换的方式
      • 在日期和字符串之间转换
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档