03 Structures in Rust

1 Types of structures


There are three kinds of structures in Rust: unit structure, tuple structure and named structure, which represent the meaning of And, and all members must be assigned values ​​when generating. The specific form is as follows:

2 Memory layout of the structure


Computers are addressed by bytes, and instructions are integer multiples of bytes. In order to maximize CPU access efficiency, the Rust compiler will optimize and rearrange the fields of the structure, such as:

But you can also arrange the structure according to the memory arrangement rules of the C language through attribute macros, such as:

3 Structures, Generics, and Trait


In most logarithmic programming languages, we will use structures to organize some data structures, and it is the same in Rust. Of particular note is its use in conjunction with generic parameters. Let's look at a more complex application scenario

In this example, we use a generic struct with multiple parameters and also use a placeholder for the phantom type PhantomData. In this way, the structure body does not need to define the parameter as a generic type in the field when declaring it. We only specify what the type is for the generic when we implement the specific trait, and we specify different generic specific types for different traits. In actual business scenarios, we often see this form of writing, pay attention to distinguish the generic constraints in different situations, and then construct the correct type

Sample code Github address:

https://github.com/shiyivei/from-principle-to-practice/blob/main/src/principle-and-practice/src/type_system/custom_struct.rs

More content, welcome to pay attention

おすすめ

転載: blog.csdn.net/weixin_51487151/article/details/129388299
03