[rust-dev] PSA: ~"string" is probably not what you want

Patrick Walton pwalton at mozilla.com
Sun Apr 28 10:45:04 PDT 2013


Just thought I'd give the mailing list a heads up that ~"string", 
besides being ugly, is generally inefficient: it allocates a string on 
the heap and frees it when it goes out of scope. There are no 
optimizations that eliminate the allocation.

If you need to compare a `~str` against a constant string, use .equiv():

     use core::cmp::Equiv;

     fn main() {
         let x = ~"foo";
         if "foo".equiv(&x) {
             println("yep");
         }
     }

This should admittedly be imported by default.

Patrick


More information about the Rust-dev mailing list