1

I have the following code I am surprised works:

struct S<'a> {
    value: &'a String,
}

fn foo(s: &S) {
    println!("{}", s.value);
}

#[allow(dead_code)]
fn main() {
    let s = S {
        value: &String::from("ABC"),
    };
    foo(&s);
}

If I see a pair of curly braces, I imagine them as a scope. So for me, the line S { value: &String::from("ABC") }; and, more importantly, the part between the curly braces represents a scope. Inside this scope, an anonymous string is created and a reference to it is taken. After the brace is closed, the string should be destroyed and the next line foo(&s) should tell me something about lifetimes, but this is not the case! Why?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
nikitablack
  • 4,359
  • 2
  • 35
  • 68
  • Note that there are other cases that curly braces appear, such as in pattern matching: `if let MyStruct { a, b } = foo { ... }` – Shepmaster Oct 13 '20 at 15:09
  • 2
    Why do the braces not create a scope? Because they're part of constructor syntax, not a block. Why does constructor syntax use `{}`? Because it mimics struct definition, and `()` and `[]` were taken. Why doesn't constructor syntax implicitly create a block? Because the language defines it that way. Why is Rust the way it is? Because Graydon woke up one day and decided to do it that way. Don't get me wrong, Rust is a well designed language, but if you're looking for deeper meaning and rationale in every language feature, you might be going a bit overboard. Some things just *are*. – trent Oct 13 '20 at 15:23
  • @trentcl that's probably better suited as an answer than a comment tbh – c-x-berger Oct 13 '20 at 16:31
  • 2
    Scopes and struct initialization using the same braces is a red herring, what you're really asking is [Why is it legal to borrow a temporary?](https://stackoverflow.com/q/47662253) – kmdreko Oct 13 '20 at 17:33

1 Answers1

0

In Rust, curly braces for structs do not denote a scope, simply the fields of a struct. It's like how you can use curly braces when invoking a macro, but those curly braces do not create a scope. If they do create a scope, it would be incredibly inconvenient, as you couldn't do something like &String::from("ABC").

Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • 1
    This doesn't really directly answer the OPs question about **why**. It only restates what they already have deduced, which is that it doesn't create a scope. *it would be incredibly inconvenient* is kind of an answer, but that would be a better answer if if could cite some sources. – Shepmaster Oct 13 '20 at 15:08