Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I think this is a good example to show people who are on the fence about postfix then. I haven't felt strongly about postfix, but this is an eye opener for me.


Yeah, I think the trick is that the theory and practice might be the same. And usually, it's the other way around; spreading it out makes it work, whereas it may not otherwise. For example:

    fn main() {
        let world = gives_string().split(" ").next();
        
        println!("{:?}", world);
    }
    
    fn gives_string() -> String {
        String::from("hello world")
    }
This will fail because the String is temporary, and we're trying to get a reference to it (via split), and so it would be deallocated at the end of the line, being a use-after-free. This, however, compiles:

    fn main() {
        let world = gives_string();
        let world = world.split(" ").next();
        
        println!("{:?}", world);
    }
    
    fn gives_string() -> String {
        String::from("hello world")
    }
We're shadowing 'world', but the underlying String now lives to the end of main, so everything works, no more use-after free.

I think before I'd want a good real-world example of where doing the multi-line thing goes wrong before I'd want to make an argument that this is why postfix is better.


This has surprised me on occasion. Shouldn't the compiler be smart enough to figure out how long to keep it around for, instead of failing to compile?


The compiler is smart enough to deduce lifetimes — that’s why it can throw a compile error — but fixing them (auto-keeping temporaries) might introduce extra memory consumption/leaks that the programmer did not intend. Requiring the programmer to explicitly assign a temporary to a variable makes the programmer’s intent more clear.

A comparison: in C++, the behavior of auto-extending the lifetime of const references to temporaries (but not non-const references) is considered a wart in the language design. (Really, you should just assign a temporary to a value because the compiler can elide the copy. : https://abseil.io/tips/101 .)


One could argue that the compiler could transform this for you. But systems languages are also about control. For someone versed in the way things are supposed to work, an owned value living longer than it should is surprising.

Tradeoffs, tradeoffs.


It's a better case for showing how to use .map().




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: