Rust (b) and variable type

rust variables

rust default variable is immutable, the variable setting variable by adding mut

fn main() {
    let _immutable_variable = 1i;
    let mut mutable_variable = 1i;

    println!("Before mutation: {}", mutable_variable);

    // Ok
    mutable_variable += 1;

    println!("After mutation: {}", mutable_variable);

    // Error!
    _immutable_variable += 1;
    // FIXME ^ Comment out this line
}

Variables with local scope, is confined within the block belongs,

fn main() {
    let a = 1;
    {
        let b = 2;
        println!("{}", b); // 2
        println!("{}", a); // 1
        let a = 3;
        println!("{}", a);// 3
    }
    println!("{}", a); // 1
    println!("{}", b);//编译不通过,b不在此作用域
}

rust type

rust language built-in types:

  • Signed positive: i8, i16, i32, i64and int(machine word)
  • Unsigned positive number: u8, u16, u32, u64and uint(machine word)
  • Float: f32,f64
  • charUnicode characters (Scalars) e.g. 'a'(4-length)
  • boolLogic type, which true, andfalse
  • Empty tuple type (), which unique values are()

Type Conversion

rust does not provide an implicit type conversion between a base type, only use askeywords explicit conversion type

let decimal = 65.4321;
let integer = decimal as u8;

expression

rust inside almost all statements are expression that has a value.
Code block is an expression, the right values can be used as an assignment statement. Value of the last expression of a code block, as the value of the code block, the value is assigned to the left. However, if the last statement of the block of code with a semicolon ;at the end, which value will be (), there will be no value.


if and else

if-else statement is an expression, each branch must return the same type to ensure type safety.

Guess you like

Origin www.cnblogs.com/ahhg/p/5439398.html