Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

50.9.1Type size

The size of the Book type can be computed by adding the type size of each field. We suppose we are on a 64-bit system:

In total the fields of the Book type add up to 24∗4+8+2+8+4=11824 * 4 + 8 + 2 + 8 + 4 = 118 bytes (three String fields plus the Vec<String> one). Since the type must be aligned on 8 bytes, the compiler adds some padding and an instance of the Book type occupies 120 bytes, as reported by std::mem::size_of::<Book>().

50.9.2Deref implementation

Here is the generic tuple structure:

We implement the new() constructor that takes a T:

The Deref trait is implemented by returning a reference to the first value of the tuple inside the deref() method:

We use MyBox to create a reference/pointer to a variable x:

Using the dereferencing operator, we can print the value pointed to by y:

5

This exercise is taken from the Rust official book. See Defining Our Own Smart Pointer.

50.9.3Shared lists

Let us import the Rc type:

We define List using Rc instead of Box:

Let us import the variants of List:

We implement a print() that we will use to print the content of a list:

We first create a list x with two values:

Couldn't automatically determine type of variable `x`.
Please give it an explicit type.

We define lists a and b with x as a sub-list for both, and the list c that uses b as a sub-list:

We can check the reference count of x and b:

Here is list a:

List b:

List c:

50.9.4Prime numbers

We import the needed structures:

We define a checker structure, that stores the tested numbers into a map:

We define the constructor that initializes an empty map:

The is_prime() method is the main entry point of our structure. It uses the cache to check if the number has already been tested, and otherwise delegates to the trial_division() method, that finds out if a number is a prime number:

We instantiate a checker:

And test it on some numbers: