0

I have a couple of pieces of code, once errors out and the other doesn't, and I don't understand why.

The one that errors out when compiling:

fn main() {
    let s1 = String::from("hello");

    println!("{}", *s1);
}

This throws: doesn't have a size known at compile-time, on the line println!("{}", *s1);

The one that works:

fn main() {
    let s1 = String::from("hello");

    print_string(&s1);

}

fn print_string(s1: &String) {
    println!("{}", *s1);
}

Why is this happening? Aren't both correct ways to access the string contents and printing them?

  • Does this answer your question? [What does “\`str\` does not have a constant size known at compile-time” mean, and what's the simplest way to fix it?](https://stackoverflow.com/questions/49393462/what-does-str-does-not-have-a-constant-size-known-at-compile-time-mean-and) – pretzelhammer Dec 23 '20 at 13:05

1 Answers1

4

In the first snippet you’re dereferencing a String. This yields an str which is a dynamically sized type (sometimes called unsized types in older texts). DSTs are somewhat difficult to use directly

In the second snippet you’re dereferencing a &String, which yields a regular String, which is a normal sized type.

In both cases the dereference is completely useless, why are you even using one?

Masklinn
  • 34,759
  • 3
  • 38
  • 57