diff options
Diffstat (limited to 'content/post/rust basic.md')
-rw-r--r-- | content/post/rust basic.md | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/content/post/rust basic.md b/content/post/rust basic.md new file mode 100644 index 0000000..8e765b9 --- /dev/null +++ b/content/post/rust basic.md @@ -0,0 +1,52 @@ ++++ +title = "rust basic -- types and ownership" +date = 2023-01-12 +[taxonomies] +categories = ["code"] +tags = ["rust"] +[extra] +math = false ++++ + +## Types +> This is a summary of rust basic knowledge I learned from (Rust the Book)[https://doc.rust-lang.org/book/] chapter 1 ~ chapter 13 +> I will use C to compare with since I familiar it. + +There are a bunch of built-in types we can work with: *scalar types* and *compound types*. +Those scalar types are just alike as C language. +| scalar types | rust | c | +| ------------- |------------- | ------- | +| integer | i(u)8/i16/i32<default>/i64 | (unsigned) char/short/int/long | +| float | f32/f64<default> | float/double | +| boolean | true/false | True/False (non-zero/zero) | +| character | char | char | + +The compound types are a bit different. rust provides many hands-on types where C type is not the same or needs to define explicitly. + +| compound type | rust | c | +| ------------- |------------- | ------- | +| struct | same | same | +| enum | enum element can be seen as key that could take value | represent numberic value, default starting from 0 | +| array | vector | array | +| string | a wraper of vector | pointer of char * | +| tuple | exist | no such type in C | + +Variable declaration in rust is kinda tricky. + +A normal declare syntax would be like `let unmutable_variable = 3`. This will imply that variable is `i32` type +since the value we assign to is a integer and the default type for integer on most OS is `i32`. +We can explicit type by using type annotation: `let unmutable_variable: u8 = 3`. This will make variable +`unmutable_variable` is `u8` type and has 3 as its value. We need to assign a value +to variable if we don't annotate type while declaration, otherwise compiler would prompt error. + +Notice that, declaration as above one won't allow us to change value, if we want to be able to change variable's +value at runtime, we need to explicit it, for security reason: +```rust +let mut mutable_variable = 3; +println!("first define: {mutable_variable}"); +mutable_variable = 5; + +println!("change value to: {mutable_variable}"); +``` + +> `println!()` is called macro, which would not cover for now. |