rust语言基础(一)

话不多说,新建工程后直接上main.rs 的代码


///Adds one  to the number given.
///
/// # Examples
///
/// ```
/// let x = add(1, 2);
///
///```

fn add(a: i32, b: i32) -> i32 {
    return a + b;
}

fn main() {
    // 使用{} 做替换符
    let a = 12;
   // a= 123 ; 会报错,a为不可变变量
    println!("a is {}", a);
    let  b = 123;
//
    println!("b is {}", b);
    let c = 123;
    let c = 456;
    println!("c is {}", c);
//重影的用法
    let x = 5;
    let x = x + 1;
    let x = x * 2;
    println!("The value of x is: {}", x);


//    let x = 2.0;  //默认不声明类型自动转换
  //  let y: f32 = 3.0;
    let sum = 5 + 10; // 加
    let difference = 95.5 - 4.3; // 减
    let product = 4 * 30; // 乘
    let quotient = 56.7 / 32.2; // 除
    let remainder = 43 % 5; // 求余
    println!("The sum  is: {0};
The difference  is: {1};
The product  is: {2};
The quotient  is: {3};
The remainder  is: {4}", sum , difference , product , quotient , remainder);

//    元组用一对 ( ) 包括的一组数据,可以包含不同种类的数据:
    let tup: (i32, f64, u8) = (500, 6.4, 1) ;
// tup.0 等于 500
// tup.1 等于 6.4
// tup.2 等于 1
    let (x, y, z) = tup;
// y 等于 6.4

   // 数组用一对 [ ] 包括的同类型数据。
    let a = [1, 2, 3, 4, 5];
// a 是一个长度为 5 的整型数组

    let b = ["January", "February", "March"];
// b 是一个长度为 3 的字符串数组

    let c: [i32; 5] = [1, 2, 3, 4, 5];
// c 是一个长度为 5 的 i32 数组

    let d = [3; 5];
// 等同于 let d = [3, 3, 3, 3, 3];

    let first = a[0];
    let second = a[1];
// 数组访问

  //  a[0] = 123; // 错误:数组 a 不可变
    let mut e = [1, 2, 3];
    e[0] = 5; // 正确

    println!("The value of e is: {}", e[0]);

    println!("fn add 的结果{}",add(3,3));
    function_name();
    another_function(5, 6);
    let x = 5;
//函数体表达式
    let y = {
        let x = 3;
        x + 1  //x + 1 之后没有分号,否则它将变成一条语句!
    };

    println!("x 的值为 : {}", x);
    println!("y 的值为 : {}", y);


    //在 Rust 中,函数定义可以嵌套:
    fn five() -> i32 {
        5
    }
    println!("five() 的值为: {}", five());
    //条件语句:
    let number = 3;
    if number < 5 {
        println!("条件为 true");
    } else {
        println!("条件为 false");
    }

    // let number = 3;
    // if number {   // 报错,expected `bool`, found integerrustc(E0308)
    //     println!("Yes");
    // }

    let a = 3; //两个函数体表达式的类型必须一样!且必须有一个 else 及其后的表达式块
    let number =   if a > 0  { 1 }  else { -1 };
    println!("number 为 {}", number);
    let mut varibablenum = 1;
    while varibablenum != 4 {
        println!("{}", varibablenum);
        varibablenum += 1;
    }
    println!("EXIT");

  //  在 C 语言中 for 循环使用三元语句控制循环,但是 Rust 中没有这种用法,需要用 while 循环来代替

    //遍历数组
    let a = [10, 20, 30, 40, 50];
    for i in a.iter() {
        println!("值为 : {}", i);
    }
    let a = [10, 20, 30, 40, 50];
    for i in 0..2 {
        println!("a[{}] = {}", i, a[i]);
    }

    let s = ['R', 'U', 'N', 'O', 'O', 'B'];
    let mut i = 0;
    loop {
        let ch = s[i];
        if ch == 'O' {
            break;
        }
        println!("\'{}\'", ch);
        i += 1;
    }
    let s = ['R', 'U', 'N', 'O', 'O', 'B'];
    let mut i = 0;
    let location = loop {
        let ch = s[i];
        if ch == 'O' {
            break i;
        }
        i += 1;
    };
    println!(" \'O\' 的索引为 {}", location);

 //   变量与数据交互方式主要有移动(Move)和克隆(Clone)两种:
  // 1、移动 多个变量可以在 Rust 中以不同的方式与相同的数据交互
    let x = 5;
    let y = x;

    let s1 = String::from("hello");
    let s2 = s1;
  //  println!("{}, world!", s1); // 错误!s1 已经失效
// 2、克隆
    let s1 = String::from("hello");
    let s2 = s1.clone();
    println!("s1 = {}, s2 = {}", s1, s2);  //不会报错
    let s = String::from("hello");
    // s 被声明有效

    takes_ownership(s);
    // s 的值被当作参数传入函数
    // 所以可以当作 s 已经被移动,从这里开始已经无效

    let x = 5;
    // x 被声明有效

    makes_copy(x);
    // x 的值被当作参数传入函数
    // 但 x 是基本类型,依然有效
    // 在这里依然可以使用 x 却不能使用 s
 // 函数结束, x 无效, 然后是 s. 但 s 已被移动, 所以不用被释放



    let s1 = gives_ownership();
    // gives_ownership 移动它的返回值到 s1

    let s2 = String::from("hello");
    // s2 被声明有效

    let s3 = takes_and_gives_back(s2);
    // s2 被当作参数移动, s3 获得返回值所有权
    // s3 无效被释放, s2 被移动, s1 无效被释放.


    let s1 = String::from("hello");
    let s2 = &s1;
    println!("s1 is {}, s2 is {}", s1, s2);
    // & 运算符可以取变量的"引用"。
    // 当一个变量的值被引用时,变量本身不会被认定无效。因为"引用"并没有在栈中复制变量的值:

    let s1 = String::from("hello");

    let len = calculate_length(&s1);

    println!("The length of '{}' is {}.", s1, len);

    let s1 = String::from("hello");
    let s2 = &s1;
 //   let s3 = s1;
 //   这段程序不正确:因为 s2 租借的 s1 已经将所有权移动到 s3,所以 s2 将无法继续租借使用 s1 的所有权。如果需要使用 s2 使用该值,必须重新租借:
    println!("{}", s2);

//下面是正确的方式:
    let s1 = String::from("hello");
    let mut s2 = &s1;
    let s3 = s2;
    s2 = &s3; // 重新从 s3 租借所有权
    println!("{}", s2);

    let s1 = String::from("run");
    let s2 = &s1;
    println!("{}", s2);
 //   s2.push_str("oob"); // 错误,禁止修改租借的值

    let mut s1 = String::from("run");
    // s1 是可变的

    let s2 = &mut s1;
    // s2 是可变的引用

    s2.push_str("oob");
    println!("{}", s2);

    let mut s = String::from("hello");

    let r1 = &mut s;
   // let r2 = &mut s;
 //   println!("{}, {}", r1, r2);
  //  这段程序不正确,因为多重可变引用了 s: 多重碰撞


   // let reference_to_nothing = dangle();
//伴随着 dangle 函数的结束,其局部变量的值本身没有被当作返回值,被释放了。但它的引用却被返回,这个引用所指向的值已经不能确定的存在,故不允许其出现。

    let s = String::from("broadcast");

        // ..y 等价于 0..y
        // x.. 等价于位置 x 到数据结束
        // .. 等价于位置 0 到结束
    let part1 = &s[0..5];
    let part2 = &s[5..9];

    println!("{}={}+{}", s, part1, part2); //切片

    let mut s = String::from("runoob");
    let slice = &s[0..3];
   // s.push_str("yes!"); // 错误 被切片引用的字符串禁止更改其值
    println!("slice = {}", slice);


    let s = "hello";
    let slice = &s[0..3];
    println!("slice = {}", slice);

    let s1 = String::from("hello");
    //快速将 String 转换成 &str:
    let s2 = &s1[..];
    println!("s2 = {}", s2);

    let arr = [1, 3, 5, 7, 9];
    let part = &arr[0..3];
    for i in part.iter() {
        println!("{}", i);
    }

    let runoob = Site {
        domain: String::from("www.runoob.com"),
        name: String::from("RUNOOB"),
        nation: String::from("China"),
        found: 2013
    };

    //远组结构体
    struct Color(u8, u8, u8);
    struct Point(f64, f64);

    let black = Color(0, 0, 0);
    let origin = Point(0.0, 0.0);

    println!("black = ({}, {}, {})", black.0, black.1, black.2);
    println!("origin = ({}, {})", origin.0, origin.1);

    #[derive(Debug)]
    struct Rectangle {
        width: u32,
        height: u32,
    }

    let rect1 = Rectangle { width: 30, height: 50 };

    println!("rect1 is {:?}", rect1);

}
// fn <函数名> ( <参数> ) <函数体> ;
// 函数名称的命名风格是小写字母以下划线分割
fn function_name() {
    println!("Hello, runoob!");
}
fn another_function(x: i32, y: i32) {
    println!("x 的值为 : {}", x);
    println!("y 的值为 : {}", y);
}

fn gives_ownership() -> String {
    let some_string = String::from("hello");
    // some_string 被声明有效

    return some_string;
    // some_string 被当作返回值移动出函数



}

fn takes_and_gives_back(a_string: String) -> String {
    // a_string 被声明有效

    a_string  // a_string 被当作返回值移出函数
}

fn takes_ownership(some_string: String) {
    // 一个 String 参数 some_string 传入,有效
    println!("{}", some_string);
} // 函数结束, 参数 some_string 在这里释放

fn makes_copy(some_integer: i32) {
    // 一个 i32 参数 some_integer 传入,有效
    println!("{}", some_integer);
} // 函数结束, 参数 some_integer 是基本类型, 无需释放

fn calculate_length(s: &String) -> usize {
    s.len()
}


// fn dangle() -> &String {
//     let s = String::from("hello");
//
//     &s
// }

//结构体
struct Site {
    domain: String,
    name: String,
    nation: String,
    found: u32
}

运行后得出各结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值