From d743c344988884c81e247a0ab9c2696912d8a1e3 Mon Sep 17 00:00:00 2001 From: garhve Date: Thu, 12 Jan 2023 19:13:20 +0800 Subject: first half of the first rust note --- public/post/rust-basic/index.html | 107 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 public/post/rust-basic/index.html (limited to 'public/post/rust-basic/index.html') diff --git a/public/post/rust-basic/index.html b/public/post/rust-basic/index.html new file mode 100644 index 0000000..262aee3 --- /dev/null +++ b/public/post/rust-basic/index.html @@ -0,0 +1,107 @@ + + + + + + +rust basic -- types and ownership | garhve's gibberish + + + + + + + + + + + +
+ + +
+ + +
+
+ +

+

rust basic -- types and ownership
+

+

+

2023-01-12
+
+ + + /code + + + + +  #rust + + +
+

+ +

+

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/i64 | (unsigned) char/short/int/long | +| float | f32/f64 | 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 typerustc
structsamesame
enumenum element can be seen as key that could take valuerepresent numberic value, default starting from 0
arrayvectorarray
stringa wraper of vectorpointer of char *
tupleexistno 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:

+
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.

+
+ +

+ + + + +
+
+ + + + + -- cgit v1.2.3-70-g09d2