Earlier quoted context omitted.
We can use match to do pattern matching: let name = match color_code { 0 => "red", 1 => "blue", 2 => "green", _ => "unknown", }; The RHS of the `=>` has to be an expression, since we're assigning it to a variable. Here, you should already see one "useful" side-effect of what you're calling "syntactic elements" (I'd perhaps call them "block statements", which I think is closer to the spirit of what you're saying.) The…
I appreciate, so much, that rust is slowly evolving into perl.
Weird Expressions in Rust
141–150 of 155 posts
Re: Weird Expressions in Rust
#142 fn main() {
println!(r#"{:X?}{}"#,
__=(|&__@_:&'_ _,|->_{[(|(..,_,__,_,):(_,_,((),),)|__..__)(__)]})({&(!(({"\"__'\\\\\
\'";(||{('\"');()})();}>=*&())|(|__|__||__|__)((()()))),&[..=..],({0__.%-//
0.;(|_:[();0],|{})([[],[],][0]);},),)}),_={(|_0_:[_;0],_:&[()]|{;_0_})({{[0;0]}},&[[
]][(0..)][{..}][0],);""},);
}
[1]: https://www.reddit.com/r/rust/comments/8p013f/comment/e094qj...Re: Weird Expressions in Rust
#143they exist because whole language built to treat expressions as firstclass citizens : blocks, ifs, matches, even macros as expressions that return values. so once you internalize that, all these weirdo one liners are artifacts. just artifact of a system where expressions compose infinitely. the syntax tree runs deeper than most people's habbits allow. you hit that depth and brain says this is wrong but compiler's all…
Likely the same should apply to expressions of type `()`.
Re: Weird Expressions in Rust
#144Earlier quoted context omitted.
That sounds superficially reasonable to me and I'm all for regularity in programming language semantics but on thinking about it further, I actually think it's a design flaw. It makes no more sense to me for "return " to have a type than it does to make "if " or "break" or "{" or any other keyword to have a type. These are syntactic elements. Rust's type system is clearly inspired by Hindley-Milner and most languages…
Respectfully, "it makes no sense to me" isn't an argument. if and break both have types in Rust as well. > don't even have a return keyword. This is because they are not procedural languages, it has nothing to do with the type system. > there is no upside that I can see to this decision in terms of language ergonomics. There's tremendous upside! That's why lots of languages choose this. For example, there is no need…
Assigning values of expressions that are purely `never`, or having values that are purely `never` or `()` as the condition in a conditional operator, should be marked as an error, like unreachable code.
Re: Weird Expressions in Rust
#145It's a C++23 library suite and lint set that eliminates:
- UB in all but the most contrived cases (I think I can get it to zero with a modest clang patch set) - bounds errors (see below) - bans all naked pointers and most references of any kind (NVRO and elision are mandated since 17, and on modern hardware like `znver5` you're usually pessimizing with e.g. `const foo_t& foo`) - and has no `usafe` keyword to fall back on, that's enforced at the conceptual module level by having things declare they are unsafe in their entirety via `extern "C"`
This stuff is really unlocked by C++23:
``` template concept SafeIndexable = requires(T& t, const T& ct, size_t idx) { { t.at(idx) } -> std::same_as; { ct.at(idx) } -> std::same_as; // Banned: t[idx] };
// Wrapper that forces .at() usage template class Safe { Container c; public: // Forward everything except operator[] template Safe(Args&&... args) : c(std::forward(args)...) {}
// Evil genius move: operator[] calls .at()
auto operator[](size_t idx) -> decltype(auto) {
return c.at(idx); // Throws on bounds violation!
}
auto operator[](size_t idx) const -> decltype(auto) {
return c.at(idx);
}
// Forward other operations
auto begin() { return c.begin(); }
auto end() { return c.end(); }
// ... etc
};// Usage: Safe> vec{1, 2, 3}; vec[10]; // Throws std::out_of_range instead of UB! ```
Re: Weird Expressions in Rust
#146this is why I like Go
I wonder, what's the "weirdest" expression in Go? Here's one: type Foo struct{} func (Foo) Bar() { println("weird...") } func main() { ([...]func(){^^len(` `): (&Foo{}).Bar})[cap(append([]any(nil),1,2,3))]() }
type __ *[]*__Re: Weird Expressions in Rust
#147Earlier quoted context omitted.
yes, but less risky (and less power full) because you often very fast can conclude that "whatever it does it's safe, sound and doesn't affect unrelated code"
And how would you conclude that "fast"? You can have UB in "safe rust". https://github.com/Speykious/cve-rs You can even disable the Type check, trait check and borrow check in "safe rust" And all of this is unsound. https://users.rust-lang.org/t/i-finally-found-the-cheat-code...
the blog focuses mainly on putting expresions into unusual positions and how some things have an implicite () type and some an implicite ! type etc.
either way if you see strange code you probably shouldn't copy/merge it without having a very good understanding of what it does
Re: Weird Expressions in Rust
#148Earlier quoted context omitted.
We've been going down this road for a long time now. E.g. "throw" is a (void-typed) expression in C++ already for similar reasons, although it doesn't go far enough without a proper bottom type. C# took it further and added the type so that you can write things like e.g. `x = y ?? throw new Error(...)`. There's no obvious reason why "return" should be conceptually different. A better question at this point, arguably,…
I considered whether to mention C# in this thread but initially decided against it because it doesn't actually have a bottom type. You can't assign a throw expression to an implicitly-typed variable, or anywhere else where it is needed to infer a type. You can only use it in places where a type is already known so the throw expression can be coerced to it. In fact, I recently ran into the finding that you can't use i…
Re: Weird Expressions in Rust
#149Earlier quoted context omitted.
return is an expression in Rust, and it fits in well. There are very few statements: https://doc.rust-lang.org/stable/reference/statements.html and a lot of expressions: https://doc.rust-lang.org/stable/reference/expressions.html
We're speaking past each other since there's "expression" as defined in the Rust specification vs "expression" as in ordinary computer science, and Rust's use of return is certainly not an expression in the latter sense. It is shoehorned into being called an expression but it has no semantically meaningful type, it is an effect. A type is (carefully but somewhat arbitrarily) assigned to it, which is why some of those…
enum Never {
}
Languages like OCaml, Haskell as well as Rust have types with no values (called uninhabited types)Re: Weird Expressions in Rust
#150Earlier quoted context omitted.
I appreciate, so much, that rust is slowly evolving into perl.
What Rust's syntax really reminds me of is Algol 68, or BLISS, both of them being these old procedural languages where everything is an expression. The "loop { ... break expr; ... }" thing reminds me of BLISS's "exitloop expr" construct.
I am incredibly amused that I got downvoted to -1 for mentioning perl though. People here are Weird.