Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in Rust struct only last field is allowed to have dynamically sized type

The chapter on unsized types in the first edition book says that:

Only the last field in a struct may have a dynamically sized type; the other fields must not. Enum variants must not have dynamically sized types as data.

Here I'm not able to understand reason behind such restriction. What make difference in last field?

like image 410
CSRd Avatar asked Oct 30 '25 23:10

CSRd


1 Answers

In Rust since the memory layout is unspecified the restriction of the dynamically sized type (DST) field being last is not technically necessary. That being said, the compiler has to know the size of all but one field and in memory the dynamically sized field has to be last, otherwise it couldn't statically calculate the offsets of all fields.

So requiring the DST to be last in the code is consistent with the required memory layout.

like image 178
cafce25 Avatar answered Nov 03 '25 02:11

cafce25



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!