Rfcs: add a macro `String` to create a new String

Created on 27 Mar 2020  路  12Comments  路  Source: rust-lang/rfcs

add a macro String to create a new String

macro_rules! String {
    ($x: expr) => {
        String::from($x)
    };
}

uasge

let  s = String!("123")
println("s = {}", s);  // s = 123 

Most helpful comment

Why? This only saves a handful of characters, so there isn't a need for a macro to handle this.

All 12 comments

Why? This only saves a handful of characters, so there isn't a need for a macro to handle this.

@KrishnaSannasi

creating a string is a very common operation, this macro will save lots of characters.
String::form("123") or "123".to_string() is so ugly, this macro makes code cleaner
String!("123") looks like more Modernized

@uploy
What about format!("123");?

@kgv

They don't seem to have the same meaning
format will output a formatted String, but String will just create a new String

so i don't think they should be mixed

@uploy
see format documentation

Creates a String

You can also use "mystr".into() in the right context.

If you really want a shorthand because String::from is "ugly" (why?), then you could make a private helper function with an even shorter name. Something like:

fn s<S: ToString>(string: &S) -> String {
    string.to_string()
}

@kgv

Creates a String using interpolation of runtime expressions

i don't know it is different or not. String! will just make a String from a string literal, but format! will get a formatted String, including some runtime variable.

@H2CO3 @Diggsey

not for a short name, because i think String!("123") or String!{"123"} looks like a construct, but other cases look like to call a function.

@uploy The Rust std is not meant to be a kitchen sink filled with every possible use-case. Because you don't mention any motivation for this beyond saving a character count, this isn't a good fit for std. If you want to use this, then you can put this macro in your crates and use it. If you don't want to do that use format, because the format macro is special cased for string literals to reduce to a to_string, so there isn't any cost to using it over your String! macro.

Note: what may be common to you (making lots of Strings) may not be common to other people, like me, who don't really need to create Strings that often. So your argument for saving about 5 characters rings hollow to me.

@KrishnaSannasi ok, I understand

You can use docs.rs/big_s

Was this page helpful?
0 / 5 - 0 ratings