Rust学习笔记(2)

2019-06-03  本文已影响0人  爱写作的harry

内容整理自:https://doc.rust-lang.org/book/title-page.html

Chapter 3:Common Programming Concepts

Variables and Mutability

Data Types

fn main() {
    let x = 2.0; // f64
      let y: 32 = 3.0; // f32
}
* Boolean
    * `let f = true;` or  `let f: bool = true;`
    * one byte in size
* Character
    * `let c = ‘z’`
    * use single quotes (string use double quotes)
    * 4 bytes in size
    * Unicode Scalar Value
    * range: U+0000 to U+D7FF and U+E000 to U+10FFFF
fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);
}
* can use period(.) to access value
fn main() {
    let x: (i32, f64, u8) = (500, 6.4, 1);

    let five_hundred = x.0;

    let six_point_four = x.1;

    let one = x.2;
}
* Arrary
    * must the same type
    * have a **fixed** length
fn main() {
    let a = [1, 2, 3, 4, 5];
    let b: [i32; 5] = [1, 2, 3, 4, 5];
}

Functions

fn main() {
    let x = 5;

    let y = {
        let x = 3;
        x + 1
    };

    println!("The value of y is: {}", y);
}
fn five() -> i32 {
    5
}

Comments

// hello, world

Control Flow

fn main() {
    let condition = true;
    let number = if condition {
        5
    } else {
        6
    };

    println!("The value of number is: {}", number);
}
fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    println!("The result is {}", result);
}
fn main() {
    let a = [10, 20, 30, 40, 50];
    let mut index = 0;

    while index < 5 {
        println!("the value is: {}", a[index]);

        index += 1;
    }
}
fn main() {
    let a = [10, 20, 30, 40, 50];

    for element in a.iter() {
        println!("the value is: {}", element);
    }
}

Chapter 4: Understanding Ownership

what is ownership

References and Borrowing

fn main() {
    let s1 = String::from("hello");

    let len = calculate_length(&s1);

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

fn calculate_length(s: &String) -> usize {
    s.len()
}
fn main() {
    let mut s = String::from("hello");

    change(&mut s);
}

fn change(some_string: &mut String) {
    some_string.push_str(", world");
}
let mut s = String::from("hello");

let r1 = &mut s;
let r2 = &mut s;

println!("{}, {}", r1, r2);

The Slice Type

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

let hello = &s[0..5];
let world = &s[6..11];
fn main() {
    let my_string = String::from("hello world");

    // first_word works on slices of `String`s
    let word = first_word(&my_string[..]);

    let my_string_literal = "hello world";

    // first_word works on slices of string literals
    let word = first_word(&my_string_literal[..]);

    // Because string literals *are* string slices already,
    // this works too, without the slice syntax!
    let word = first_word(my_string_literal);
}
let a = [1, 2, 3, 4, 5];

let slice = &a[1..3];
上一篇 下一篇

猜你喜欢

热点阅读