5 ms·
Incidentally, I'm not personally very fond of "assigning an if-expression to a variable" since it disconnects the variable name from the value it gets. An examp
by edflsafoiewq 5y ago
Incidentally, I'm not personally very fond of "assigning an if-expression to a variable" since it disconnects the variable name from the value it gets. An example with two variables illustrates the point:
let (value, weight) = let (value, weight)
if values.empty() { if values.empty() {
(0, 1.0) value = 0
} else { weight = 1.0
(values[0], 1/values.len()) } else {
} value = values[0]
weight = 1/values.len()
}
I think the right (the "old way") is more readable. However it requires the variables be mutable or declaration be separable from initialization.
- verdagon 5y agoHuh! I think you're right. I never realized that the old way was clearer. I like your second example there. The compiler could probably very easily ensure that a variable was initialized before first usage. Thank you for the idea and insight!
- brundolf 5y agoThat seems like more of an issue with tuples than with expressive if/else. Tuples are known for having this easy-to-miss disconnection (take for example a function call that returns a tuple, which couldn't be avoided like the above situation can)
- olodus 5y agoI agree. I feels like this naming disconnect would not exist in this case if you would work with a record/struct. That is what you sacrefice with tuples.
- codefined 5y agolet { value, weight } = if values.empty() { { value: 0, weight: 1.0 } } else { { value: values[0], weight: 1 / values.len() } } Using JS style object expansion, instead of tuple expansion.
- edflsafoiewq 5y agoYou would use a struct here to initialize two variables? The disconnect already exists, multiple variables or many else-if branches just accentuates it.
- kungito 5y agoWhile in Rust this is only a cosmetic difference I still prefer the first approach as there is less to read to understand what is happening. Also once you are familiar with the language construct of if expression it is even faster to connect what goes where. When looking at the thing on the right I had to carefully go through each expression to distinguish which tokens are just fillers and which contain relevant information as you cannot be sure the general if behaves in the way you would think it would in this case.