0

What is the difference between the following two programs in Rust in terms of string usage?

fn main() 
{
    let s1 = "hello";
    println!("{}, world!", s1);
}

And,

fn main() 
{
    let s1 = String::from("hello");
    println!("{}, world!", s1);
}

??

user366312
  • 16,949
  • 65
  • 235
  • 452
  • _**quick!**_ - to the Godbolt machine! – Dai Aug 06 '22 at 08:37
  • **I return**: Here's a comparison with `opt-level=1` optimizations: https://godbolt.org/z/c9EjhjPas - note that Rust's famed zero-cost language-features actually have a surprisingly high cost when compiled with optimizations disabled (so all those `std::option` wrapper values will probably exist somewhere in memory instead of all their value copying code being completely elided at higher optimization levels - so I guess try that link again but change it to `opt-level=2` or `opt-level=3` - and other options - and compare yourself. – Dai Aug 06 '22 at 08:49
  • 2
    In the first example, `s1` is a string literal and has type `&'static str`. This will be compiled right into the data section of the final binary. In the second example, `s1` is an owned string and has type `String`. Because it is dynamic, i.e. growable, it allocates its data on the heap at runtime, meaning any access to it will have to go through the heap as well. – isaactfa Aug 06 '22 at 09:44

0 Answers0