Reputation: 42062
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?
Upvotes: 5
Views: 1388
Reputation: 11
I am using snippets to reduce the pain a little bit.
Using vscode
and rust-analyzer
// settings.json
{
"rust-analyzer.completion.snippets.custom": {
"String::from prefix": {
"prefix": "s",
"body": "String::from(\"$1\")$0",
"description": "String::from(\"…\")",
},
"String::from postfix": {
"postfix": "s",
"body": "String::from(${receiver})",
"description": "String::from(…)",
},
}
}
Upvotes: 0
Reputation: 18079
The macro by Jmb works fine, but I prefer to use plain functions where possible. (I also prefer post-fix operations over prefix+postfix ones)
So this is the variant I have used:
pub trait ToStringExt : ToString {
/// Simply an alias for `.to_string()`.
fn s(&self) -> String {
self.to_string()
}
}
impl<T> ToStringExt for T where T: ToString {}
And then to use it:
use to_string_ext::ToStringExt;
fn main() {
let my_str: String = "some string".s();
}
If the only case where you want this shorthand is converting a &str
into a String
, then this is a narrower alternative: (which I prefer nowadays)
pub trait ToOwnedExt where Self : ToOwned {
/// Simply an alias for `.to_owned()`.
fn o(&self) -> <Self as ToOwned>::Owned {
self.to_owned()
}
}
impl<T: ?Sized> ToOwnedExt for T where T: ToOwned {}
And then to use it:
use to_owned_ext::ToOwnedExt;
fn main() {
let my_str: String = "some string".o();
}
Upvotes: 0
Reputation: 23443
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"), });
}
Upvotes: 7