Rust programming video tutorial (Advanced) – 027_ 3 advanced features 3

Time:2021-9-20

Video address

Headline address:https://www.ixigua.com/i677586170644791348…
Station B address:https://www.bilibili.com/video/av81202308/

Source address

GitHub address:https://github.com/anonymousGiga/learn_rus…

Explanation content

Dynamically sized types, sometimes referred to as “DST” or “unspecified types”, allow us to handle types whose size is known only at run time.
(1) STR is a DST; We don’t know how long the string is until runtime.
Example: / / the following code is wrong

let s1: str = "Hello there!"; 
let s2: str = "How's it going?";

The correct code is:

let s1: &str = "Hello there!"; 
let s2: &str = "How's it going?";

explain:
&STR is two values: STR’s address and its length. In this way, & STR has a size that can be known at compile time: it is twice the length of use. In other words, we always know the size of & STR no matter how big the string is.
Therefore, the golden rule of dynamic size type is derived: the value of dynamic size type must be placed after some pointer. Such as box or RC, & STR, etc.
Another dynamic size type is trait. Each trait is a dynamic size type that can be referenced by its name. In order to use traits with trait objects, they must be placed after pointers, such as & trait or box (RC can also be used).
(2) Sized trait
To handle DST, rust uses sized trait to determine whether the size of a type is known at compile time. This trait is automatically implemented for types whose size is known by the compiler at compile time.
example:

FN generic < T > (T: T) {// T is the type of size known at compile time 
    // --snip-- 
}

Equivalent to

FN generic < T: sized > (T: T) {// T is the type of size known at compile time 
    // --snip-- 
}

How can this restriction be relaxed? Rust provides the following methods:

fn generic<T: ? Sized > (T: & T) {// T may or may not be sized 
    // --snip-- 
}

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Linghu rushed