Rust代码示例——2.基础类型

Rust提供了各种不同的基础类型,如下所述:

标量类型:

  1. 有符号整形:i8,i16,i64,i128和i size(指针的大小)
  2. 无符号整形:u8,u16,u64,u128和usize(指针的大小)
  3. 浮点类型:f32,f64
  4. 字符类型:char(unicode标量值),例如:'a', 'α' and '∞'(4个字符)
  5. 布尔类型:true和false
  6. 单元类型:(),是一个空的元祖类型()
  7. 尽管单元类型的值是一个空的元祖,但是它不被认为是一个组合类型,因为它不含有多个值。

组合类型:

  1. 数组:[1, 2, 3]
  2. 元祖:(1, true)

变量总是需要进行类型声明,数字也通过后缀或默认类型进行额外的声明。整形默认是i32类型,浮点型默认是f64类型。注意,rust也可以通过上下文推断出类型。

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`


    // A type can also be inferred from context.

    let mut inferred_type = 12; // Type i64 is inferred from another line.

    inferred_type = 4294967296i64;


    // A mutable variable's value can be changed.

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

    mutable = 21;


    // Error! The type of a variable can't be changed.

    mutable = true;


    // Variables can be overwritten with shadowing.

    let mutable = true;


    /* Compound types - Array and Tuple */


    // Array signature consists of Type T and length as [T; length].

    let my_array: [i32; 5] = [1, 2, 3, 4, 5];


    // Tuple is a collection of values of different types

    // and is constructed using parentheses ().

    let my_tuple = (5u32, 1u8, true, -5.04f32);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值