CS110L-Week 1 Exercises: Hello world

第一周作业链接: https://reberhardt.com/cs110l/spring-2020/assignments/week-1-exercises/

第一周的作业主要是熟悉Rust的工具链安装和一些Rust语法

第一部分 helloworld

安装工具链,访问Rust官方: https://www.rust-lang.org/tools/install

helloworld

cargo 提供了命令行来创建rust项目

cargo new helloworld

然后就可以cargo build 或者cargo run

➜  helloworld git:(main) ✗ tree
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
    ├── CACHEDIR.TAG
    └── debug
        ├── build
        ├── deps
        │   ├── helloworld-681c2ade33f71cab
        │   └── helloworld-681c2ade33f71cab.d
        ├── examples
        ├── helloworld
        ├── helloworld.d
        └── incremental
            └── helloworld-3gmsxxterlir4
                ├── s-fw1pxstg53-1leo6ld-2439fudoc3hif
                │   ├── 14i0bcdbfi2ugad2.o
                │   ├── 15ne1gcrt9rvpglq.o
                │   ├── 18abmkatn3n4l0hu.o
                │   ├── 27s29o1kcsspusdg.o
                │   ├── 2xwm4i2jxgoiz5co.o
                │   ├── 3050lnwbirtj1yb5.o
                │   ├── dep-graph.bin
                │   ├── gp126zvew3eug9.o
                │   ├── q4wkdgq1k2s2v4m.o
                │   ├── query-cache.bin
                │   └── work-products.bin
                └── s-fw1pxstg53-1leo6ld.lock

从上面可以看到,整个项目的结构。src/main.rs 是源代码 target中的目录为编译生成的目录

main.rs 自带hello,world

fn main() {
    println!("Hello, world!");
}

Cargo.toml是包依赖

[package]
name = "helloworld"
version = "0.1.0"
authors = ["Jimmy Xiang <xxg1413@gmail.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

第二部分 Rust语法热身

    let n:i32 = 1;
    let n = 1;


    //可变类型
    let mut  n = 0;
    n = n + 1;

    //Rust有两种字符串: &str和String
    let s: &str = "hello,world"; //只读数据段

    let mut s: String = String::from("hello,");
    s.push_str("world");
    println!("{}", s);


     //动态数组
     let mut v: Vec<i32> = Vec::new();
     v.push(2);
     v.push(3);

     
     //固定大小数组
     let mut arr: [i32; 4] = [0,2,4,8];
     arr[0] = -2;
     println!("{}", arr[0]+arr[1]);


     //迭代器
     for i in arr.iter()
     {
         println!("{}",i);
     }


     //while
    let mut sum = 0;
    let mut i = 0;
     while i < 20 
     {
         i += 1;
         sum += i;

     }

     println!("sum={}",sum);


    //loop  它有助于编译器对变量初始化进行一些假设。
    let mut i = 0;
    loop {

        i += 1;

        if i == 10 {
            break;
        }
    }

    println!("i={}",i);

    //函数

    fn mysum(a: i32, b:i32) -> i32 
    {
        a + b  //Rust是一种基于表达式的 语言,不需要分号

        //a + b ; 会出错
    }
     
    println!("sum={}", mysum(1,2));

练习:

use std::collections::HashSet;
//练习

fn add_n(v: Vec<i32>, n: i32) -> Vec<i32> {
    

    let mut result: Vec<i32> = Vec::new();

    for i in v.iter() {
        result.push(i+n)
    }

    result
}

fn add_n_inplace(v: &mut Vec<i32>, n: i32) {

    let mut i = 0;

    while i < v.len() {

        v[i] = v[i] + n;
        i = i + 1;
    }
}

fn dedup(v: &mut Vec<i32>) {


    let mut hs = HashSet::new();
    let mut i = 0;

    while i < v.len() {

        if !hs.contains(&v[i]) {

            hs.insert(v[i]);
            i += 1;

        }  else {

            v.remove(i);
        }
    
    }
}



#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_add_n() {
        assert_eq!(add_n(vec![1], 2), vec![3]);
    }

    #[test]
    fn test_add_n_inplace() {
        let mut v = vec![1];
        add_n_inplace(&mut v, 2);
        assert_eq!(v, vec![3]);
    }

    #[test]
    fn test_dedup() {
        let mut v = vec![3, 1, 0, 1, 4, 4];
        dedup(&mut v);
        assert_eq!(v, vec![3, 1, 0, 4]);
    }
}

第三部分 Hangman

代码: https://github.com/xxg1413/CS110L/tree/main/Assignments/week1/Hangman

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

您正在使用您的 WordPress.com 账号评论。 注销 /  更改 )

Facebook photo

您正在使用您的 Facebook 账号评论。 注销 /  更改 )

Connecting to %s