let Some(x) = foo() else { return 42 };745 karma · joined November 1, 2021
let Some(x) = foo() else { return 42 };You can write it like this:
let foo_result = match foo() {
Ok(v) => v,
Err(e) => return Bar::Fail(e)
};The code above can be written as:
let foo = foo()?;The main difference I see is that in Rust it will also work with your own custom types, not just optional.
fn make_bla() -> Option<Bla> {
// this either returns a valid Bla, or None
}
if let Some(bla) = make_bla() {
// bla is now the unwrapped valid type
} else {
// make_bla() returned None
}
..or with the '?' operator (early return) let bla = make_bla().ok_or(InvalidBla)?;
..or with let_else (nightly only but should be stable Soon(tm)) let Some(bla) = make_bla() else { return Err(InvalidBla) }
..or panic on None let bla = make_bla().unwrap();I also personally find Go syntax to be horrible, especially now with generics.
For example for this code:
trait Foo {
fn foo(&self) {}
}
struct Bar;
impl Foo for Bar {}
mod test {
use super::Bar;
fn test() {
Bar.foo();
}
}
22 | Bar.foo();
| ^^^ method not found in `Bar`
|
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
20 | use crate::Foo;
|For rust-analyzer it's blocked on improvements in Chalk.
Instead you should use rust-analyzer which will soon become the official rust extension.
https://marketplace.visualstudio.com/items?itemName=matklad....
But it's not a problem because you build a new version of cargo with an older version of cargo that of course can parse TOML.
[0] https://github.com/rust-lang/cargo/blob/master/Cargo.toml
Generics and trait bounds are in the language from the start.
So you can write this function like this:
fn twiddle<T: IntoIterator<Item = Foozle>>(foozles: T)
Which is 100% idiomatic today and is even preferred by some people over using impl Trait