Skip Navigation

Search

Rust Programming @lemmy.ml

Can I specify what subset of errors a function can return?

I have two functions that are similar but can fail with different errors:

 rust
    
#[derive(Debug, thiserror::Error)]
enum MyError {
  #[error("error a")]
  MyErrorA,
  #[error("error b")]
  MyErrorB,
  #[error("bad value ({0})")]
  MyErrorCommon(String),
}

fn functionA() -> Result<String, MyError> {
  // can fail with MyErrorA MyErrorCommon
  todo!()
}

fn functionB() -> Result<String, MyError> {
  // can fail with MyErrorB MyErrorCommon
  todo!()
}

  

Is there an elegant () way I can express this?

If I split the error type into two separate types, is there a way to reuse the definition of MyErrorCommon?


() by "elegant" I mean something that improves the code - I'm sure one could define a few macros and solve that way, but I don't want to go there

edit: grammar (rust grammar)

Rust Programming @lemmy.ml

one-liner to avoid "temporary value dropped while borrowed"?

(I'm just starting off with rust, so please be patient)

Is there an idiomatic way of writing the following as a one-liner, somehow informing rustc that it should keep the PathBuf around?

 rust
    
// nevermind the fully-qualified names
// they are there to clarify the code
// (that's what I hope at least)

let dir: std::path::PathBuf = std::env::current_dir().unwrap();
let dir: &std::path::Path   = dir.as_path();

// this won't do:
// let dir = std::env::current_dir().unwrap().as_path();
 

  

I do understand why rust complains that "temporary value dropped while borrowed" (I mean, the message says it all), but, since I don't really need the PathBuf for anything else, I was wondering if there's an idiomatic to tell rust that it should extend its life until the end of the code block.