Impl AsRef<str> with on-fly String

Hi,

/// Scalar Value string type.
#[derive(Clone, PartialEq)]
pub struct SvStr {
    m_chars: Vec<char>,
}

impl AsRef<str> for SvStr {
    fn as_ref(&self) -> &str {
        self.m_chars.into_iter().collect::<String>().as_ref()
    }
}

Getting:

cannot move out of `self.m_chars` which is behind a shared reference
move occurs because `self.m_chars` has type `Vec<char>`, which does not implement the `Copy` traitrustcE0507
lib.rs(29, 22): `self.m_chars` moved due to this method call
collect.rs(261, 18): this function takes ownership of the receiver `self`, which moves `self.m_chars`
cannot return reference to temporary value
returns a reference to data owned by the current functionrustcE0515
lib.rs(29, 9): temporary value created here

I did try cloning m_chars.

You can't. Something will need to own that String.
AsRef is probably the wrong thing for whatever usecase you have here.

1 Like