• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

2.2Rust数据类型

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 

 2.2 数据类型

Rust has four primary scalar types: integers, floating-point numbers, Booleans, and characters. 

 整数类型

 

 u32,this type declaration indicates that the value it’s associated with should be an unsigned integer (signed integer types start with i, instead of u) that takes up 32 bits of space. 

Additionally, the isize and usize types depend on the kind of computer your program is running on: 64 bits if you’re on a 64-bit architecture and 32 bits if you’re on a 32-bit architecture.

 

Note that all number literals except the byte literal allow a type suffix, such as 57u8, and _ as a visual separator, such as 1_000.

整数溢出

Let’s say that you have a u8, which can hold values between zero and 255. What happens if you try to change it to 256? This is called “integer overflow,” and Rust has some interesting rules around this behavior. When compiling in debug mode, Rust checks for this kind of issue and will cause your program to panic, which is the term Rust uses when a program exits with an error. 

In release builds, Rust does not check for overflow, and instead will do something called “two’s complement wrapping.” In short, 256 becomes 0, 257 becomes 1, etc. Relying on overflow is considered an error, even if this behavior happens. If you want this behavior explicitly, the standard library has a type, Wrapping, that provides it explicitly.

 

浮点类型

Rust’s floating-point types are f32 and f64, which are 32 bits and 64 bits in size, respectively. The default type is f64 because on modern CPUs it’s roughly the same speed as f32 but is capable of more precision.

fn main() {
    let x = 64.0 ; //f64
    let y: f32 = 32.0; //f32
    println!("64:{},32:{}",x,y);
}
The f32 type is a single-precision float, and f64 has double precision.

 

 

数字运算

fn main() {
    // addition
    let _sum = 5 + 10;

    // subtraction
    let _difference = 95.5 - 4.3;

    // multiplication
    let _product = 4 * 30;

    // division
    let _quotient = 56.7 / 32.2; //1.7608695652173911 小数点后16位
    let _ff32 = 7f32 / 3f32;   //2.3333333  7位小数

    // remainder
    let _remainder = 13 % 5;  //3
    println!{"32位除法:{}",_ff32}
    println!{"默认64位除法:{}",_quotient};
    println!{"求余:{}",_remainder};
}

 整数与浮点数不可以混合运算,比如 let _cc = 10 * 3.0; 会报以下错误

^ no implementation for `{integer} * {float}`

error: Could not compile `datatype`.

 

布尔类型

fn main() {
    let _t = true;
    let _f: bool = false; // with explicit type annotation
}

 字符类型

fn main() {
    let _a = 'z';
    let _b = 'ℤ';
    let _c = 'Z';
}
 Rust’s char type represents a Unicode Scalar Value, which means it can represent a lot more than just ASCII. Accented letters; Chinese, Japanese, and Korean characters; emoji; and zero-width spaces are all valid char values in Rust. Unicode Scalar Values range from U+0000 to U+D7FF and U+E000 to U+10FFFF inclusive. However, a “character” isn’t really a concept in Unicode, so your human intuition for what a “character” is may not match up with what a char is in Rust.

 

复合类型

Compound types can group multiple values into one type. Rust has two primitive compound types: tuples and arrays.

元组存放数据的数据类型可以不同,数组则必须是相同类型。

元组

A tuple is a general way of grouping together some number of other values with a variety of types into one compound type. Tuples have a fixed length: once declared, they cannot grow or shrink in size.

Each position in the tuple has a type, and the types of the different values in the tuple don’t have to be the same. 

 

fn main() {
    let _tup: (i32, f64, u8) = (500, 6.4, 1);
    let _aa = (1,2.3,"wa ka ka ");
    let (_x,_y,_z) = _aa;
    println!("The value of z is:{}",_z)
}
This program first creates a tuple and binds it to the variable tup. It then uses a pattern with let to take tup and turn it into three separate variables, x, y, and z. This is called destructuring, because it breaks the single tuple into three parts. 

 In addition to destructuring through pattern matching, we can access a tuple element directly by using a period (.) followed by the index of the value we want to access. 

 

fn main() {
    let _x: (i32, f64, u8) = (500, 6.4, 1);
    let _five_hundred = _x.0;
    let _six_point_four =_x.1;
    let _one = _x.2;
    println!("第三个元素:{}",_one);
}

数组类型 

Unlike a tuple, every element of an array must have the same type. Arrays in Rust are different from arrays in some other languages because arrays in Rust have a fixed length, like tuples.

fn main() {
    let _a = [1, 2, 3, 4, 5];
}

Arrays are useful when you want your data allocated on the stack rather than the heap or when you want to ensure you always have a fixed number of elements. An array isn’t as flexible as the vector type, though. A vector is a similar collection type provided by the standard library that is allowed to grow or shrink in size. If you’re unsure whether to use an array or a vector, you should probably use a vector. 

 It’s very unlikely that such a program will need to add or remove months, so you can use an array because you know it will always contain 12 items

fn main() {
    let _a = [1, 2, 3, 4, 5];
    let _months = ["January", "February", "March", "April", "May", "June", "July",
              "August", "September", "October", "November", "December"];
}

Arrays have an interesting type; it looks like this: [type; number]. For example:

fn main() {
    let _b: [i32; 5] = [1, 2, 3, 4, 5];
}

访问数组元素

fn main() {
    let _b: [i32; 5] = [1, 2, 3, 4, 5];
    let _c1 = _b[0];
    let _c2 = _b[1];
}

数组越界

fn main() {
    let a = [1, 2, 3, 4, 5];
    let index = 10;

    let element = a[index];

    println!("The value of element is: {}", element);
}

编译阶段不会报错,在运行时会报错

[root@itoracle src]# cargo build
   Compiling datatype v0.1.0 (/usr/local/automng/src/rust/test/datatype)                                                 
    Finished dev [unoptimized + debuginfo] target(s) in 1.39s                                                            
[root@itoracle src]# cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s                                                            
     Running `/usr/local/automng/src/rust/test/datatype/target/debug/datatype`
thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 10', src/main.rs:5:19
note: Run with `RUST_BACKTRACE=1` for a backtrace.

 数据遍历

pub fn test_for(){
    let aa = [1,2,3,4,5];
    let mut index = 0;
    for bb in aa.iter() {
        println!("{}:{}",index,bb);
        index = index +1;
    }
}

pub fn test_for2(){
    let aa = [1,2,3,4,5];
    for (index,&bb) in aa.iter().enumerate() {
        println!("{}:{}",index,bb);
    }
}

 

初始化指定长度数组

pub fn test() {

    let buffer = [0; 1024];
    for (idx, &val) in buffer.iter().enumerate(){
        println!("{}:{}",idx,val);
    }
}
......
......
......
1015:0
1016:0
1017:0
1018:0
1019:0
1020:0
1021:0
1022:0
1023:0

 

 

类型转换

fn data02(){
    println!("-------显式类型转换-------");
    let a = 1;
    let b = a as f64;
    let c = b * 2.0;
    println!("c={}",c);  //c=2
    println!("-------------------------------------------------------");
}

 

 

let guess: u32 = "42".parse().expect("Not a number!");

 

 
format的使用

不做任何类型格式化原样输出
format!("{}", foo) -> "3735928559"

以十六进制数的形式输出
format!("0x{:X}", foo) -> "0xDEADBEEF"

以八进制的形式输出
format!("0o{:o}", foo) -> "0o33653337357"

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
MATLAB中如何定义全零的一维数组发布时间:2022-07-18
下一篇:
****- 五课时精通matlab小波分析-Matlab发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap