3 ms·
In Rust, you can write: let x = 5i32; Sadly it's nowhere near as elegant for string literals.
by nyanpasu64 7y ago
In Rust, you can write:
let x = 5i32;
Sadly it's nowhere near as elegant for string literals.
- littlestymaar 7y ago> Sadly it's nowhere near as elegant for string literals. What do you mean? For string literals you just do let foo= "bar"; and that's it. BTW, in Rust you can omit most variable type annotations since the compiler is able to infer them. You have to give type annotations to functions though.
- nyanpasu64 7y agoI meant turning string literals into heap-allocated strings.
- littlestymaar 7y agoAh yes, in this case it's indeed a bit more verbose: let foo= "bar".to_string(); It's on purpose though, because Rust likes to make heap allocations explicit, and I find it fine to be honest, but you mileage may vary.
- nyanpasu64 7y agohttps://users.rust-lang.org/t/to-string-vs-to-owned-for-string-literals/1441 https://users.rust-lang.org/t/to-string-vs-to-owned-for-stri... > I’m more fond of using .into(). It requires adding type hints in some cases, but for most cases it is shorter than the alternatives. Especially when passing a string literal to a function that requires String. > Now that specialization for str::to_string() has landed, we can safely say that to_string() has the same performance as to_owned(), and thus to_string() should be used since it’s more clear > I now strongly prefer to_owned() for string literals over either of to_string() or into(). yay language complexity
- littlestymaar 7y ago> yay language complexity You could argue that Rust strings are complex, because they are : having 8 "string-like" types (owned strings vs string slices (references), cstr/cstring, path and pathbuf, osstr/osString) is complex, but having three different methods doing exactly the same thing isn't. Yes it's redundant, but what would you rather have : str as the only easily convertible type with no to_string method? Or the only reference type without to_owned? No ability to use into for strings while it works everywhere else? Obviously, redundancy is better than theses alternatives.