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

Adding DisplayStr impl for &dyn DisplayStr #33

Merged
merged 2 commits into from
Feb 15, 2023

Conversation

luketpeterson
Copy link
Contributor

This is related to #32

The following code would work if &dyn DisplayStr implemented DisplayStr

    let template = "{body} = {some_number:2.4}";

    let mut data: HashMap<String, &dyn DisplayStr> = HashMap::new();
    data.insert("body".to_string(), &"This is a string");
    data.insert("some_number".to_string(), &5.0);

    let output = strfmt(template, &data)?;

A HashMap of &dyn DisplayStr is more efficient than the current best solution for heterogeneous input types, which is Box, because each box requires a separate allocation.

Thank you.

…heterogeneous inputs without requiring boxing
@vitiral
Copy link
Owner

vitiral commented Feb 13, 2023

This needs tests. Does the example code actually run with just this change? It's been years since I seriously wrote rust, if this is all it takes then dyn is cooler than I realized.

Also, why &"This is a string"? Why is the &? Is that some kind of signal to the compiler to make it dyn?

@luketpeterson
Copy link
Contributor Author

I pushed a new test to the branch. test_heterogenous_values

What's happening is this:

  • "This is a string" has type &str
  • There was already an implementation for DisplayStr for &str
  • I could only add an &str as a value to a HashMap<_, &str>, but then I couldn't add an integer to that same map
  • &"This is a string" has type &&str, which can be cast to &dyn DisplayStr because &str implements DisplayStr
  • Likewise & f64 can also become &dyn DisplayStr, so they can coexist in the same HashMap

@vitiral vitiral merged commit fdd7de8 into vitiral:master Feb 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants