1

Rust allows declaring a structure inside a function but it doesn't allow assigning a variable with it in a simple way.

fn f1() -> (something) {
    struct mystruct {
        x: i32,
    }

    let s = mystruct;

    s
}

fn f2(s: something) {
    let obj = s { x: 5 };
    println!(obj.x);
}

fn main() {
    let s = f1();
    f2(s);
}

Is it possible to store a struct into a variable in a different way? How do I write the struct type correctly? In my project, I want to declare a struct inside a function and create instances inside of another one.

7
  • 2
    It looks like you started in programming with Rust. Please read the book as it explains all the details on how to write Rust programs and the syntax. If you still have questions, please comt back and ask them. Commented Jan 18, 2019 at 8:13
  • @hellow Yes, I did start programming in Rust. But it does not mean that my question is incorrect. For example, in Python it is not a problem to store a class into a variable. Commented Jan 18, 2019 at 8:15
  • I edited my question. If a macros helps I would be happy to see an example. Commented Jan 18, 2019 at 8:19
  • 1
    Thanks for the edit, but now I ask you something. How is somebody outside of function f1 supposed to know how your struct mystruct looks like? How do they know what kind of members it has, what size they are? It is not possible, you cannot use mystruct outside of your f1 function Commented Jan 18, 2019 at 8:20
  • 1
    @hellow I edited the code again. I forgot to create an instance. Commented Jan 18, 2019 at 8:22

1 Answer 1

6

How to store a struct into a variable in Rust?

Rust is a statically typed language, and as such it is not possible to store a type into a variable, then use this variable to construct an instance of the type.

This is the reason you are not able to express what the type of s is; there is simply no vocabulary in the language for this.


Depending on what you want to do, you may wish to look into:

  • Generics: fn f2<T: Default>() would allow creating an instance of any type T implementing the Default trait.
  • Run-time polymorphism: A factory function FnOnce(i32) -> Box<Trait> could produce an instance of any type implementing Trait from a i32.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for nice explanation.
@Fomalhaut: You're welcome. Coming from a highly dynamic language like Python you are bound to bump into limitations that we're taking for granted; I'm looking forward to your future [rust] questions :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.