Live data from Hacker News

Weird Expressions in Rust

wakunguma.com

141–150 of 155 posts

Re: Weird Expressions in Rust

#141

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.

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.

Re: Weird Expressions in Rust

#142
Many moons ago[1] I wrote this, which seems appropriate to share here:

    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

#143
post #5

they 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…

This is logically sound, but pragmatically not so. I wish the compiler could issue a warning or even an error if an expression of type `never` is used in a logical condition, like that of an `if`. While such cases might have rare legitimate uses (e.g. some edge cases of macro expansion, etc), I'd like it to be marked explicitly, similar to `unsafe`, e.g. with some `allow_never_as_condition` marker.

Likely the same should apply to expressions of type `()`.

Re: Weird Expressions in Rust

#144
post #32

Earlier 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…

This makes sense because the `match` returns a union of u32 and `never`.

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

#145
I'm actually working on a project I'm quite serious about but jokingly refer to as "Ergonomic Rust", which would make all of it a weird expression in Rust.

It'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

#146

this 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))]() }

I have a personal fondness for silly variations of

  type __ *[]*__

Re: Weird Expressions in Rust

#147
post #82

Earlier 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...

yes, but that is a different kind of unreadable code then in the blog

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

#148
post #119
post #92

Earlier 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…

Yes, this is a good example of how not having the bottom type actually makes things messier overall. Without it you have to make those case-by-case hacks. With it, all the stuff that people actually want to write and that makes sense "just works", and sure, there's more stuff that you could write that doesn't make sense as well, but it's not something that people might end up writing accidentally by mistake and get wrong behavior.

Re: Weird Expressions in Rust

#149

Earlier 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…

Return has the ! type. It's a type with no values, similar to an enum without variants, like this:

    enum Never {
    }
Languages like OCaml, Haskell as well as Rust have types with no values (called uninhabited types)

Re: Weird Expressions in Rust

#150

Earlier 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.

There's so many programming languages (low barrier to create) that there's a ton of overlap and evolutionary changes/similarities between them. I was thinking of perl's "do { x } while foo" style constructs in this particular case.

I am incredibly amused that I got downvoted to -1 for mentioning perl though. People here are Weird.

Post reply on HN