To define-then-use or not, that is the question
⚓ Rust 📅 2026-01-12 👤 surdeus 👁️ 1So, I thought a nice goal for 2026 was to finally get to know rust better and I'm doing quite okay I think. Since I want to do rust and not my-usual-mash-up-of-languages in rust I thought I'd ask your opinions.
In some languages you absolutely have to define your items first (as in, above the first usage) with some minor exceptions (e.g. ocaml) and in others you can access them as long as their "associated value" is defined before usage (e.g. js). In rust it seems you can use whatever is statically know (?).
So compare the following two examples and tell me which one you think is more idiomatic:
impl Foo for Bar {
fn f() -> Y {
fn some_complex_predicate(x: &X) -> bool;
fn some_specific_function(x: &X) -> Y;
match foo {
A(x) if some_complex_predicate(&x) => some_specific_function(x)
}
}
}
which forces a reader to at least skim over some code that isn't immediately relevant
or
impl Foo for Bar {
fn f() -> Y {
return match foo {
A(x) if some_complex_predicate(&x) => some_specific_function(x)
};
fn some_complex_predicate(x: &X) -> bool;
fn some_specific_function(x: &X) -> Y;
}
}
which uses early returns to sort of mimic haskells where. If rust didn't have where as a keyword with similar semantics already I'd pick the first option, but since it does... what's your opinion here?
Note: please keep in mind that I just started with rust a week ago after reading the book, rust by example and a bit of the nomicon. Maybe I'm missing some crucial piece to e.g. write "open traits" which would allow defining the functions outside of f.
6 posts - 3 participants
🏷️ Rust_feed