Return formatted string as ref to bytes

Viewed 68

I have the following struct:

struct CompareUrl {
    repo: String,
    left: String,
    right: String,
}

And I want this struct to return itself in bytes.

impl CompareUrl {
    pub fn as_bytes(&self) -> &[u8] {
        format!(
            "https://github.com/{}/compare/{}...{}",
            self.repo,
            self.left,
            self.right
        ).as_bytes()
    }
}

But it complains about ownership:

cannot return reference to temporary value
returns a reference to data owned by the current function

It seems that it works for (&str).as_bytes(), but not for (String).as_bytes(). My attempt was to solve this like that:

impl CompareUrl {
    pub fn as_bytes(&self) -> &[u8] {
        format!(
            "https://github.com/{}/compare/{}...{}",
            self.repo,
            self.left,
            self.right
        ).as_str().as_bytes()
    }
}

But it raises the same error. How can I solve it?

1 Answers

You can't return a reference to a value owned by the function, like the String the format! macro produces, because it gets dropped when the function returns and the reference would be invalid. Use the into_bytes method to turn your String into an owned Vec of bytes instead:

impl CompareUrl {
    pub fn as_bytes(&self) -> Vec<u8> {
        format!(
            "https://github.com/{}/compare/{}...{}",
            self.repo,
            self.left,
            self.right
        ).into_bytes()
    }
}
Related