Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove the Error bound from get_or_try_insert_with method #37

Merged
merged 2 commits into from
Sep 7, 2021

Conversation

tatsuya6502
Copy link
Member

In #23, the trait bounds for E was changed from Box<dyn Error + ...> to Error + ....

Current

use std::error::Error;

pub fn get_or_try_insert_with<F, E>(&self, key: K, init: F) -> Result<V, Arc<E>>
where
    F: FnOnce() -> Result<V, E>,
    E: Error + Send + Sync + 'static,

This pull request removes the Error bound from E.

After

pub fn get_or_try_insert_with<F, E>(&self, key: K, init: F) -> Result<V, Arc<E>>
where
    F: FnOnce() -> Result<V, E>,
    E: Send + Sync + 'static,

We are doing this because having Error is not necessary and too strict. For example, the following code will not compile with the current bounds, because anyhow::Error does not implement std::error::Error trait.

// Cargo.toml
// [dependencies]
// anyhow = "1"

use moka::sync::Cache;

fn main() -> anyhow::Result<()> {
    let cache: Cache<i32, i32> = Cache::new(1024);

    let _ = cache
        // The return type of the init closure is Result<i32, anyhow::Error>.
        // Note that anyhow::Error does not implement std::error::Error.
        .get_or_try_insert_with(0, || Err(anyhow::anyhow!("Always fail")))
        // Wrap Arc<anyhow::Error> with anyhow::Error.
        .map_err(|e| anyhow::anyhow!(e))?;
    Ok(())
}
error[E0277]: the trait bound `anyhow::Error: std::error::Error` is not satisfied
  --> src/bin/main1.rs:13:10
   |
13 |         .get_or_try_insert_with(0, || Err(anyhow::anyhow!("Always fail")))
   |          ^^^^^^^^^^^^^^^^^^^^^^ the trait `std::error::Error` is not implemented for `anyhow::Error`

error: aborting due to previous error

Removing the Error bound resolves the compile error.

@tatsuya6502 tatsuya6502 self-assigned this Sep 7, 2021
@tatsuya6502 tatsuya6502 added the enhancement New feature or request label Sep 7, 2021
@tatsuya6502 tatsuya6502 added this to the v0.6.0 milestone Sep 7, 2021
Copy link
Member Author

@tatsuya6502 tatsuya6502 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merging

@tatsuya6502 tatsuya6502 merged commit 90969d3 into master Sep 7, 2021
@tatsuya6502 tatsuya6502 deleted the remove-error-bound branch September 7, 2021 12:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant