Rust code uses snake case as the conventional style for function and variable names.
Statements are instructions that perform some action and do not return a value.
Expressions evaluate to a resulting value.
The type of returned values need to be declared after an arrow (->). In Rust, the return value of the function is synonymous with the value of the final expression in the block of the body of a function. You can also return early from a function by using the return keyword.
1 2 3
fnplus_one(x: i32) ->i32 { x + 1 }
Comments
In Rust, comments must start with two slashes and continue until the end of the line. For comments that extend beyond a single line, you’ll need to include // on each line.
Control Flow
if
ifexpression’s condition don’t need “()” and all arms should have types that are compatible.
1 2 3 4 5 6 7
leta = if number % 4 == 0 { 4 } elseif number % 3 == 0 { 3 } else { 0 }
loops
Rust has three kinds of loops: loop, while, and for. loop has no conditions and run forever until break.
1 2 3 4 5
fnmain() { loop { println!("again!"); } }
while has an condition like if.
1 2 3
while number != 0 { number = number - 1; }
for is specially for iteration.
1 2 3
forelementin [1,2].iter() { println!("the value is: {}", element); }
If a module named foo has no submodules, you should put the declarations for foo in a file named foo.rs.
If a module named foo does have submodules, you should put the declarations for foo in a file named foo/mod.rs.
Privacy Rules
An item (mods or functions in mod) is private unless set to pub.
If an item is public, it can be accessed through any of its parent modules.
If an item is private, it can be accessed only by its immediate parent module and any of the parent’s child modules.
Referring to Names in Different Modules
The use keyword brings only what we’ve specified into scope: it does not bring children of modules into scope.
To bring all the items in a namespace into scope at once, we can use the * syntax, which is called the glob operator.
Use super to access a parent module, or use leading colons to start from the root and list the whole path.
scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); scores.entry(String::from("Blue")).or_insert(50);//inserting a Value if the key has no value
letscores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect(); // HashMap<_, _> is needed here because it’s possible to collect into many different data structures and Rust doesn’t know which you want unless you specify.
letmut map = HashMap::new(); map.insert(field_name, field_value); // field_name and field_value are invalid at this point, try using them and // see what compiler error you get!
//iteration for (key, value) in &scores { println!("{}: {}", key, value); }