Trivial shadowing

Hello, I am now working with the following code:

while let Some(msg) = {
    let msg: Data = msg;
    // ...

Here it implements Stream<Item=Data> + Sized, but the IDE intellisense fails to give msg exact type annotation for kind of reason (that's not the point here). So I use shadowing just to better cooperate with IDE.

I wonder that (1) Will that be zero cost? (2) Is this workaround idiomatic enough in rust world? Thanks!

Unless you are compiling without optimizations, the compiler will certainly eliminate any things like two moves in succession that could be one.

I don't recall seeing this anywhere but I also don't recall seeing other solutions to exactly this problem — it doesn't come up much that there is literally no operation to be done at the same time. That is, I'd usually expect to see

let msg: Data = msg.into();

or some other operation within the statement; your case is unusual in that you need to specify the type and don't also have some operation to perform. I'm not saying you shouldn't do this — just that it is not a common enough problem to have an established idiom.

You could also write

let _: Data = msg;

which doesn't even cause a semantic move, let alone a physical one. I suspect that might be slightly more surprising to most readers, though. Also, it has the disadvantage of counting as a use of msg, so if you neglect to use it later you won't get an unused variable warning.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.