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 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?

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 :

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.

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