Is merging a &str slice and a String slice the idiomatic way to create a text?

Suppose I have a text:

Hey <username>,

Could you confirm your profile for us?
username: <username>
address: <address>
phone: <phone_number>

Thank you!

Is the idiomatic way to create such a text, using a slice of constant &str's
and a slice of Strings and then merging them together?
And if so, how does one go about it?

const ping_slice_one = &["ping"; 5];

pub struct App {
    pong_one: String,
    pong_two: String,
    pong_three: String,
    pong_four: String,
}

impl App {
    pub fn new() -> App {
        App {
            pong_one: String::from("pong"),
            pong_two: String::from("pong"), 
            pong_three: String::from("pong"), 
            pong_four: String::from("pong"),
        }
    }
    
    pub fn pong_slice_one() -> &[String] {
        &[pong_one, pong_two, pong_three, pong_four];
    } 
    
    pub fn merge_into_text(str_slice: &[&str] ,string_slice: &[String]) -> &str {
        // merging goes here
        "" // stub
    }
}

fn main() {
    let mut app = App::new();
    
    assert_eq!(app.merge_into_text(ping_slice, app.pong_slice_one()), 
    "ping pong ping pong ping pong ping pong ping");
}

(Playground)

for very simple use cases, you can use slice::join() or maybe slice::concat(), but in general I suggest use format!() (also, returning a &str slice for runtime computed string values doesn't really make sense, just return an owned String).

for even more complex situations, you can use a templating engine library.

2 Likes

Somewhere in between those options, define a struct that holds the data and implement fmt::Display.

6 Likes

A good idea, but there's more than one form I want to print out.
Suppose that text is part of a ConfirmationForm struct,
I would need to add an extra struct, RegistrationForm
that would need to copy the data from one form to the other,
correct?

It's true that you can only have one fmt::Display implementation per struct, so if you have multiple forms based on one central data-storing type, you'll need an additional type per form with this approach.

They can borrow the data instead of copying the data, though.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.