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

"In addition, there are some variables such as locks and scope_guards that are only used for their side effects"

...

"This solution is also similar to other languages’ features or conventions"

As far as I know, in Rust you can't use "_" for that, as the value will be dropped right away, so the mutex/resource/etc. won't live for the scope.



No, it lives until the end of its last scope regardless of name


This is not a name, it's the specific choice not to assign it to any name, and so your parent was correct that it's dropped immediately.

https://rust.godbolt.org/z/P1z7YeP4Y

As you see, Rust specifically rejects this code because it's never what you meant, either write explicitly "I want to take and then immediately give away the lock" via drop(LOCK.lock()) (this really might be what you wanted, the Linux kernel does this in a few places) or write an actual named placeholder variable like in my third example function.


But on the other hand the motivating problems noted in C++ don't exist. It is 100% legal to completely rebind a variable in the same scope, it never warns that `_` variables are unused nor about unused `_` prefixed variables. I think `_` being immediately dropped is maybe one of those unfortunate decisions we'll look back in 20 years and regret.


Ever heard of `-Wunused-variable`?

> rebind a variable in the same scope

But only re-assigning values of the same type. Otherwise:

  int x = foo();
  int x = bar();
  error: redefinition of 'x'
and,

  int x = foo();
  long x = bar();
  error: redefinition of 'x'
What are you talking about?


In rust it’s perfectly legal to do

    let x = foo()
    let x = bar()
Regardless of the return types. That obviates a lot of the motivating problem that the c++ paper is contorting itself to fix


Yes, borrowing some stuff from functional languages (like the ability to shadow variables) gave Rust a good boost in ergonomics.


> This is not a name, it's the specific choice not to assign it to any name

Yeah, it's the same in c#. This is noticeable when in the same scope you can have multlple "_" vars. If these were actual names, they would be a name clash.

One of the uses is take some parts of a tuple return and ignore the others.

e.g.

var (thingIwant, _, _, _) = FunctionThaReturnsATupleOfFourThings();

There are three "_" in that expression, and they are different vars with different types. They don't really have the same name, they don't have names at all.




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

Search: