Mon Nov 28 2022
In Rust, what distinguishes a struct method from an associated function (in Python we could say a method from a static method) is simply the fact that the first parameter is self
. Really reminds me of Python.
struct MyStruct {}
impl MyStruct {
// Associated function
fn my_associated_function(foo: String) {}
// Method
fn my_method(self, foo: String) {}
}
On the contrary to Python, self
is meaningful and cannot be replaced with another label.
Also, Rust doesn’t allow named or keyword parameters, only positional parameters.
When writing Rust code, the compiler and linter can be a bit annoying because we specified a return type and we have not finished writing our function yet. If you want to get rid for now of the compiler errors about this, you can add the macro todo!()
into your function.
You can find the documentation here.
You can have a reference of a reference of a reference of a ref…
Which means this is perfectly valid in Rust:
let foo = "foo";
let new_string = format!("My new string: {}", &&&&&&&&&&&foo);
Rust has shorthand property names as in Javascript.
struct Person {
age: u8
}
// ...
let age = 18;
// Both are equivalent
Person({age: age});
Person({age});
You can implement a trait like this:
struct Person {}
impl Drop for Person {
fn drop(&mut self) {}
}
You can read more about traits here. The Drop
trait is interesting because it defines a method that will be called before the variable is dropped in memory.
You can use index integers in SQL’s GROUP BY and ORDER BY, relating to the columns in the SELECT statement (index starts at 1).
SELECT id, name
FROM account
ORDER BY 2;
is equivalent to:
SELECT id, name
FROM account
ORDER BY name;