became_fish ,
@became_fish@jorts.horse avatar

is there a way out of this pattern in :

let val = some_function();  
if val.is_none() {  
 return Ok(...);  
}  
let val = val.unwrap();  

that doesn't involve a bunch of nested match statements?

Tintenfisch3 ,

@became_fish
This is what let else was made for:

let Some(val) = some_function() else {  
 return Ok(...);  
};  
Muddobbers ,
@Muddobbers@infosec.exchange avatar

@became_fish

if I'm understanding it correctly..

some_function() is returning an Option, if it's None then you return out from where you are, otherwise you continue and do your thing with the contents of the value 'val'?

Maybe:

if let Some(val) = some_function() {<br></br> println!{"{}", val)<br></br>} else {<br></br> return Ok(...)<br></br>
became_fish OP ,
@became_fish@jorts.horse avatar

@Muddobbers this works, but i'm looking for something that won't increase the indent level (if i do this five times in a function, i don't want my code to look like a pyramid). i think let... else that other replies have brought up is what i'm looking for here

mendelsshop ,

@became_fish

You can use a let else.

let val = some_function();  
let Some(val) = val else {  
 return Err(...);  
}  
bryan ,
@bryan@toot.cafe avatar

@became_fish

Not much better, but we use

let Some(val) = some_function() else {  
 return OK(…);  
};  

pretty regularly.

If you’re returning an Err instead of an Ok then

let val = some_function().ok_or(Error::…)?;  

works nicely.

livingcoder ,
@livingcoder@universeodon.com avatar

@became_fish I'm generally okay with this pattern, but I change it up slightly to assignments from match or blocks:

From match:

let value = match some_function() {  
 Some(value) =&gt; value,  
 None =&gt; return Ok(...),  
};  

From block:

let value = {  
 let value = some_function();  
 if value.is_none() {  
 return Ok(...);  
 }  
 value.unwrap()  
};  
became_fish OP ,
@became_fish@jorts.horse avatar

@livingcoder wait, that second one - you can use a block as a value?

livingcoder ,
@livingcoder@universeodon.com avatar

@became_fish Yeah, I find it quite helpful to separate parsing logic out from the root of the function to keep the variable names clean in the root. I end up creating steps as blocks.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • random
  • test
  • worldmews
  • mews
  • All magazines