Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between declaration and definition of say a struct in Rust

Tags:

rust

I'm weak on understanding the definitions of "declaration" and "definition" in relation to Rust. The Rust reference says that struct fields are dropped in declaration order. Does this mean in the order of the struct when it is originally created {?definition/declaration?},

struct Example {
    x: i32,
    y: i32,
}

or when values are actually added to the struct {?definition/declaration?} (which can be in an order different from the original creation),

fn foo -> Example {
    Example {
         y: 43,
         x: 42,
    }
} 

I'm unclear on which of these is the declaration and which is the definition.

I tried to print a message when y dropped but my code failed to compile.

like image 430
cyborg Avatar asked Oct 24 '25 05:10

cyborg


1 Answers

I don't think there is a distinction between the two for structs in Rust.

In some languages (like C), there may be a difference between declaring that a type exists ("there is some type named Example") and defining the structure of that type ("the type named Example has fields x and y"). However, there is not syntax in Rust that separates them, they are one in the same. The Rust Reference and Rust Book seem to prefer calling it a "definition", though you are right the documentation on destructors says "fields of a struct are dropped in declaration order".

The "declared order" is what you see in the struct's definition. Thus x will be dropped before y. The latter example is instantiating a struct, and if the documentation meant that instead it would call it the "instantiation order", "initialization order", or something similar.


None of the above is to say that the distinction doesn't exist in Rust, just not in respect to structs:

  • With traits, the definition of the trait may only include declarations of the associated functions and other items that will be defined by the trait implementations.
  • You can also see verbiage for "declaration" when talking about introducing variables where the "definition" can be done separately (e.g. let a; a = 5 is valid) though usually that is called "initializing" instead of "defining" but you would be understood either way.
  • There may be extern types eventually which would involve a "declaration" of a type but not a "definition", since that'd be used for opaque handles to types defined outside of Rust.
like image 198
kmdreko Avatar answered Oct 26 '25 18:10

kmdreko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!