Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can you return a private struct from a closure

Rust normally has strict privacy laws, you can’t return a private type from a public function.

However, it seems like you are able to return a type created in a closure from that closure. But why? Why are you allowed to return a private struct from a closure?

fn main () {
    let closure = || {
        struct Sample;

        Sample
    };
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because you can still do things with it. The structure isn’t sealed inside the closure, it just so happens that we can’t use the name Sample directly outside of the closure. But we can still access its methods. Consider

fn main () {
  let closure = || {
    struct Sample;

    impl Sample {
      fn say_hello(&self) {
        println!("Hello, world! :)");
      }
    }

    Sample
  };
  let s = closure();
  s.say_hello();
}

The main function still knows that s has type Sample, and we can still call inherent methods like say_hello on it. The fact that you, as the programmer, can’t say the name of the structure, is irrelevant.


Just to make it perfectly clear, based on feedback in the comments. Local structures and fn functions in Rust (i.e. structures and functions written inside other functions) are not actually local. They’re internally hoisted to the enclosing module from a visibility standpoint. A function can’t own a structure, only a module can. You can’t reference the name Sample in the module scope, but that’s where it’s being hoisted to internally. If it helps, you can think of it as though Sample is being lifted to a top-level struct __mangledname_internal_Sample at the top of your file. It’s still there, just not with a name that you can access.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading