Skip to content

from_iter on heapless::String should be generic over any iterator that yields a type that implements AsRef<str> #630

Open

Description

@redzic

You currently cannot use from_iter directly with a &[CompactString] for example. You have to do .into_iter().map(...) which is annoying. I ended up building my own helper function for this but it would be nicer if the heapless crate itself provided this generic impl.

This is my helper function:

pub fn build_hstring<const N: usize, I, S>(iter: I) -> heapless::String<N>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    let mut new = heapless::String::<N>::new();
    for c in iter {
        new.push_str(c.as_ref()).expect("build_hstring: capacity exceeded");
    }
    new
}

Activity

  1. sgued commented on Nov 7, 2025

    @sgued
    Contributor

    That would make a lot of sense, do you know why std's String does not implement this either? We try to follow the standard library's API's for consistency.

  2. workingjubilee commented on Nov 8, 2025

    @workingjubilee

    We cannot add the blanket impl as it would be a breaking change.

    You may add impl FromIterator<CompactString> for String directly if that type is local to your crate.

    In addition, these sorts of implementations can make type inference worse by adding lots of ambiguous candidates. I constantly wish .into::<T>() was provided by the standard library because I wind up using .into() but inference fails.

  3. workingjubilee commented on Nov 8, 2025

    @workingjubilee

    Mind, it is possible this implementation would be fine in practice because of the specific point in inference it would be at (argument, essentially, instead of output) and if so that would be good to know in case we ever get the power to add non-breaking blankets. We used to think specialization would enable this. Not so much anymore, but that doesn't rule out some other "quasi-specialization" feature that does work for this specific case.

    Because of the context-laden nature of type inference, while we can be certain that more-than-1 candidate can complicate things, it's hard to find out what will work adequately without just... trying.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions