Shorthand way of generating owned strings

Viewed 216

Given the following struct (in practice, its bigger than this):

#[derive(Deserialize, Debug)]
struct Parameter {
    name: String,
    value: String,
}

If I want to create an instance of this (for tests, etc.):

Parameter {
    name: "name".to_string(),
    value: "value".to_string()
}

I have to call to_string on the end of all my values. This is a bit annoying. Is there a shorthand way of creating an owned string?

1 Answers

You could always shorten it with a macro:

macro_rules! s {
    ($s:expr) => { $s.to_string() }
}

#[derive(Debug)]
struct Parameter {
    name: String,
    value: String,
}

fn main() {
    println!("{:?}", Parameter { name: s!("foo"), value: s!("bar"), });
}

Playground

Related