2 ms·
You can write it just fine if `const Z` is itself nested inside a function definition. And this isn't really any different from variable references, if you thi
by int_19h 1y ago
You can write it just fine if `const Z` is itself nested inside a function definition.
And this isn't really any different from variable references, if you think about it. If you have an expression (x + 1), you can only use it somewhere where there's an `x` in scope. Similarly, you can only use `return` somewhere where there's a function to return from in scope. Indeed, you could even make this explicit when designing the language! A function definition already introduces implicit let-definitions for all arguments in the body. Imagine if we redefined it such that it also introduces "return" as a local, i.e. given:
fn foo(x: i32, y: i32) -> i32 {
...
}
the body of the function is written as if it had these lines prepended:
let x = ...;
let y = ...;
let return = ...;
...
where "return" is a function that does the same thing as the statement. And similarly for break/continue and loops.
The thing that actually makes these different from real variables is that they cannot be passed around as first-class values (e.g. having the function pass its "return" to another function that it calls). Although this could in fact be done, and with Rust lifetime annotations it would even be statically verifiable.
- kelnos 1y ago> You can write it just fine if `const Z` is itself nested inside a function definition. You can't, actually: 'const' is special in that it's not considered by the compiler to be inside a function definition, even if it is (and the compiler will tell you, "return statement outside of function body"). But that doesn't invalidate your point; in a way it supports it: 'return' can only be used in function contexts, just like 'continue' or 'break' can only be used in loop contexts.
- tialaramex 1y agoYou can do this: const ONE: i32 = { const fn foolish() -> i32 { return 1 } foolish() }; But yes, your larger point is exactly correct, the constant, even if it happens to be defined inside a function body, is not itself inside a function body and so we obviously can't return from it. It is also not inside an expression we can break out of (Rust allows you to break out of any expression, not just loops). It's a constant, like 5 is a constant, or 'Z' is a constant - this is not C or C++ where "const" means "actually a variable".