边做边学Rust之原生数据类型

2. 原生数据类型

Rust提供了一些原生数据类型。包括:

  • 有符号整形:i8,i16,i32,i64和isize(指针大小)
  • 无符号整形:u8,u16,u32,u64和usize(指针大小)
  • 浮点类型:f32,f64
  • 字符类型是Unicode值,像‘a’,'α' 和 '∞' (4 字节长)
  • bool类型非true即否
  • 单元类型(),同时值也为()
  • 数组,例如[1, 2, 3]
  • 元组,例如(1, true)
变量可以使用注解标注类型。数字可以可以通过后缀后者默认的方式进行主机。整形默认为i32,浮点型默认为f64.

fn main() {
    // Variables can be type annotated.
    let logical: bool = true;

    let a_float: f64 = 1.0;  // Regular annotation
    let an_integer   = 5i32; // Suffix annotation

    // Or a default will be used.
    let default_float   = 3.0; // `f64`
    let default_integer = 7;   // `i32`

    let mut mutable = 12; // Mutable `i32`.

    // Error! The type of a variable can't be changed
    //mutable = true;
}

程序编译结果:

   Compiling primitives v0.1.0 (file:///root/rust/examples/primitives)
src/main.rs:3:9: 3:16 warning: unused variable: `logical`, #[warn(unused_variables)] on by default
src/main.rs:3     let logical: bool = true;
                      ^~~~~~~
src/main.rs:5:9: 5:16 warning: unused variable: `a_float`, #[warn(unused_variables)] on by default
src/main.rs:5     let a_float: f64 = 1.0;  // Regular annotation
                      ^~~~~~~
src/main.rs:6:9: 6:19 warning: unused variable: `an_integer`, #[warn(unused_variables)] on by default
src/main.rs:6     let an_integer   = 5i32; // Suffix annotation
                      ^~~~~~~~~~
src/main.rs:9:9: 9:22 warning: unused variable: `default_float`, #[warn(unused_variables)] on by default
src/main.rs:9     let default_float   = 3.0; // `f64`
                      ^~~~~~~~~~~~~
src/main.rs:10:9: 10:24 warning: unused variable: `default_integer`, #[warn(unused_variables)] on by default
src/main.rs:10     let default_integer = 7;   // `i32`
                       ^~~~~~~~~~~~~~~
src/main.rs:12:9: 12:20 warning: unused variable: `mutable`, #[warn(unused_variables)] on by default
src/main.rs:12     let mut mutable = 12; // Mutable `i32`.
                       ^~~~~~~~~~~
src/main.rs:12:9: 12:20 warning: variable does not need to be mutable, #[warn(unused_mut)] on by default
src/main.rs:12     let mut mutable = 12; // Mutable `i32`.
                       ^~~~~~~~~~~
     Running `target/debug/primitives`


2.1 Literals and operators


整数1,浮点数1.2,字符‘a’,字符串“abc”,布尔型true和元类型()可以使用literals表示。


整数可以使用十六进制、八进制或者二进制表示,它们需要分别使用前缀:0x, 0o, 0b。

下划线可以插入到数字中间以增强可读性,例如1_000跟1000相同,0.000_001跟0.000001相同。

我们需要告诉编译器我们使用literals的类型。现在来说我们使用u32后缀来暗示literal是一个32位无符号整形,使用i32后缀来暗示一个32位符号整形。

操作符和他们的优先级跟C语言类似。

fn main() {
    // Integer addition
    println!("1 + 2 = {}", 1u32 + 2);

    // Integer subtraction
    println!("1 - 2 = {}", 1i32 - 2);
    // TODO ^ Try changing `1i32` to `1u32` to see why the type is important

    // Short-circuiting boolean logic
    println!("true AND false is {}", true && false);
    println!("true OR false is {}", true || false);
    println!("NOT true is {}", !true);

    // Bitwise operations
    println!("0011 AND 0101 is {:04b}", 0b0011u32 & 0b0101);
    println!("0011 OR 0101 is {:04b}", 0b0011u32 | 0b0101);
    println!("0011 XOR 0101 is {:04b}", 0b0011u32 ^ 0b0101);
    println!("1 << 5 is {}", 1u32 << 5);
    println!("0x80 >> 2 is 0x{:x}", 0x80u32 >> 2);

    // Use underscores to improve readability!
    println!("One million is written as {}", 1_000_000u32);
}

程序执行结果:

1 + 2 = 3
1 - 2 = -1
true AND false is false
true OR false is true
NOT true is false
0011 AND 0101 is 0001
0011 OR 0101 is 0111
0011 XOR 0101 is 0110
1 << 5 is 32
0x80 >> 2 is 0x20
One million is written as 1000000

2.2 元组

元组是一个不同类型值的一个集合。元组使用括号( )构建,并且每个元组是一个有类型签名(T1,T2,...)的值,T1,T2是其成员的类型。函数可以使用元组或者返回元组,因为元组何以承载任意多个值。

// Tuples can be used as function arguments and as return values
fn reverse(pair: (i32, bool)) -> (bool, i32) {
    // `let` can be used to bind the members of a tuple to variables
    let (integer, boolean) = pair;

    (boolean, integer)
}

fn main() {
    // A tuple with a bunch of different types
    let long_tuple = (1u8, 2u16, 3u32, 4u64,
                      -1i8, -2i16, -3i32, -4i64,
                      0.1f32, 0.2f64,
                      'a', true);

    // Values can be extracted from the tuple using tuple indexing
    println!("long tuple first value: {}", long_tuple.0);
    println!("long tuple second value: {}", long_tuple.1);

    // Tuples can be tuple members
    let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);

    // Tuples are printable
    println!("tuple of tuples: {:?}", tuple_of_tuples);

    let pair = (1, true);
    println!("pair is {:?}", pair);

    println!("the reversed pair is {:?}", reverse(pair));

    // To create one element tuples, the comma is required to tell them apart
    // from a literal surrounded by parentheses
    println!("one element tuple: {:?}", (5u32,));
    println!("just an integer: {:?}", (5u32));

    //tuples can be destructured to create bindings
    let tuple = (1, "hello", 4.5, true);

    let (a, b, c, d) = tuple;
    println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);
}

程序运行结果:


long tuple first value: 1
long tuple second value: 2
tuple of tuples: ((1, 2, 2), (4, -1), -2)
pair is (1, true)
the reversed pair is (true, 1)
one element tuple: (5,)
just an integer: 5
1, "hello", 4.5, true

2.3 数组和切片

数组是相同类型T的一些对象的集合,存储在连续内存上。数组可以使用[ ]创建,并且他们的大小在编译时可以确定的,是它们类型签名的一部分[T;size]。


切片跟数组类似,但是他们的大小在编译时是未知的。相反,一个切片是一个two-word对象,第一个字指向数据的指针,第二个字是切片的长度。切片可以用来借用一个数组的某一部分,并拥有类型签名&[T]。

use std::mem;

// This function borrows a slice
fn analyze_slice(slice: &[i32]) {
    println!("first element of the slice: {}", slice[0]);
    println!("the slice has {} elements", slice.len());
}

fn main() {
    // Fixed-size array (type signature is superfluous)
    let xs: [i32; 5] = [1, 2, 3, 4, 5];

    // All elements can be initialized to the same value
    let ys: [i32; 500] = [0; 500];

    // Indexing starts at 0
    println!("first element of the array: {}", xs[0]);
    println!("second element of the array: {}", xs[1]);

    // `len` returns the size of the array
    println!("array size: {}", xs.len());

    // Arrays are stack allocated
    println!("array occupies {} bytes", mem::size_of_val(&xs));

    // Arrays can be automatically borrowed as slices
    println!("borrow the whole array as a slice");
    analyze_slice(&xs);

    // Slices can point to a section of an array
    println!("borrow a section of the array as a slice");
    analyze_slice(&ys[1 .. 4]);

    // Out of bound indexing yields a panic
    println!("{}", xs[5]);
}

程序执行结果:

first element of the array: 1
second element of the array: 2
array size: 5
array occupies 20 bytes
borrow the whole array as a slice
first element of the slice: 1
the slice has 5 elements
borrow a section of the array as a slice
first element of the slice: 0
the slice has 3 elements
thread '<main>' panicked at 'index out of bounds: the len is 5 but the index is 5', <anon>:35
playpen: application terminated with error code 101


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值