Studying test in day2

#![crate_type = "cdylib"]
// 常量
const PI: f32 = 3.1415927;
/*
变量不可变性
*/
fn variable_and_mutable() {
    let mut x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);

    // 遮蔽变量
    let x = x + 1;
    {
        let x = x * 2;
        println!("The inner x is: {}", x);
    }
    println!("The outer x is: {}", x);
}

/*
数据类型
*/
fn data_type() {
    // 整型
    let x: i8 = 127;
    let x2: u8 = 255;
    let x3: isize = 63; // 由系统决定数据类型
                        // 浮点型
    let y: f32 = 1.1;
    let y2: f64 = 36.3333333;
    // 布尔型
    let z: bool = false;
    // 字符型
    let a: char = '我';

    // 复合类型
    // 元组
    let tup: (bool, f64, i32) = (true, 3.14, 65);
    println!("tup.1 is: {}", tup.1);
    // 数组
    let arr: [i32; 2] = [7, 3];
}

/*
函数:
**语句和表达式:语句不返回值,表达式要返回值
*/

fn return_five_plus(x: i32) -> i32 {
    x + 1
}

fn statement_expression() {
    // let x = (let y = 6);
    let y = {
        let x = 1;
        x + 1
    };
    println!("y = {}", y);

    println!("return_five_plus value is: {}", return_five_plus(5));
}

/*
控制流
*/
fn control_flow() {
    // 分支流
    let condition = false;
    let x = if condition { "five" } else { "six" };
    println!("x is : {}", x);

    // 循环流
    // loop循环
    let mut counter = 0;
    let y = loop {
        counter += 1;
        if counter == 20 {
            break counter * 2;
        }
    };
    println!("y = {}", y);
    // for循环
    let arr: [usize; 5] = [1, 2, 3, 4, 5];
    //for letement in &arr {
    for element in arr.iter() {
        println!("letement is {}", element);
    }
}

/*
所有权 ownerShip
 所有权规则:
   1、Rust 中的每一个值都有一个被称为其所有者(owner)的变量。
   2、值在任一时刻有且只有一个所有者。
   3、当所有者(变量)离开作用域,这个值将被丢弃。
*/
fn ownership(){
    let s:&str = "hello";
    println!("s = {}", s);
    
    let mut s2 = String::from("hello");
    s2.push_str(" world");
    println!("s2 = {}", s2);
    
    // 变量与数据的拷贝 copy 
    // 具有copy trait 的数据类型有 整型、浮点型、布尔型、字符型、元组
    {
        let x = 5;
        let y = x;
    }
    
    // 变量与数据的移动和克隆
    {
        let s = String::from("hello");
        let s2 = s.clone();
        println!("s = {}, s2 = {}", s, s2);
    }
}


fn main() {
    //variable_and_mutable();
    //println!("PI is {}", PI);
    //data_type();
    //statement_expression();
    //control_flow();
    ownership();
}

(Playground)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.