大家好
今天 完成 2024年自動駕駛OS開發(fā)訓(xùn)練營-初階營第四期-導(dǎo)學(xué)
Day2用 rustlings 練習(xí) Rust 語言 -Move Semantics
在正式開營之前战授,我們特別設(shè)置了導(dǎo)學(xué)階段剩檀,旨在幫助大家更好地迎接頗具挑戰(zhàn)性的項目實戰(zhàn)。
導(dǎo)學(xué)階段包括一系列精心準備的視頻課程和配套習(xí)題塑悼。
github鏈接:https://classroom.github.com/a/7jeNPL16
第一階段作業(yè) rustlings ranking:https://cicvedu.github.io/rust-rustlings-semester-4-ranking/
第二階段作業(yè):https://docs.qq.com/doc/DSk5xTHRJY1FZVUdK
沖??呀裸弦!
Structs
Rust has three struct types: a classic C struct, a tuple struct, and a unit struct.
Further information
我的題目
https://github.com/cicvedu/rustlings-semester-4-watchpoints
Enums
Rust allows you to define types called "enums" which enumerate possible values.
Enums are a feature in many languages, but their capabilities differ in each language. Rust’s enums are most similar to algebraic data types in functional languages, such as F#, OCaml, and Haskell.
Useful in combination with enums is Rust's "pattern matching" facility, which makes it easy to run different code for different values of an enumeration.
Further information
This section explores a case study of Option, which is another enum defined by the standard library.
enum Option<T> {
None,
Some(T),
}
Strings
Rust has two string types, a string slice (&str
) and an owned string (String
).
We're not going to dictate when you should use which one, but we'll show you how
to identify and create them, as well as use them.
Further information
C++ 默認綁定的祟同,只有指針類型 在&
https://github.com/cicvedu/rustlings-semester-4-watchpoints
創(chuàng)建ssh key,用于ssh方式克隆github代碼理疙。
在linux環(huán)境下晕城,使用ssh-keygen -t rsa -b 4096 -C "你的郵箱"命令,創(chuàng)建ssh key窖贤,
下面的選項全部直接敲回車即可砖顷。 隨后使用 cat ~/.ssh/id_rsa.pub
Modules
In this section we'll give you an introduction to Rust's module system.
Further information
Hashmaps
A hash map allows you to associate a value with a particular key.
You may also know this by the names unordered map in C++,
dictionary in Python or an associative array in other languages.
This is the other data structure that we've been talking about before, when
talking about Vecs.
Further information
**
****# Options
Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not.
Option types are very common in Rust code, as they have a number of uses:
- Initial values
- Return values for functions that are not defined over their entire input range (partial functions)
- Return value for otherwise reporting simple errors, where None is returned on error
- Optional struct fields
- Struct fields that can be loaned or "taken"
- Optional function arguments
- Nullable pointers
- Swapping things out of difficult situations
Further Information
Error handling
Most errors aren’t serious enough to require the program to stop entirely.
Sometimes, when a function fails, it’s for a reason that you can easily interpret and respond to.
For example, if you try to open a file and that operation fails because the file doesn’t exist, you might want to create the file instead of terminating the process.
Further information
Generics
Generics is the topic of generalizing types and functionalities to broader cases.
This is extremely useful for reducing code duplication in many ways, but can call for rather involving syntax.
Namely, being generic requires taking great care to specify over which types a generic type is actually considered valid.
The simplest and most common use of generics is for type parameters.
Further information
Traits
A trait is a collection of methods.
Data types can implement traits. To do so, the methods making up the trait are defined for the data type. For example, the String
data type implements the From<&str>
trait. This allows a user to write String::from("hello")
.
In this way, traits are somewhat similar to Java interfaces and C++ abstract classes.
Some additional common Rust traits include:
-
Clone
(theclone
method) -
Display
(which allows formatted display via{}
) -
Debug
(which allows formatted display via{:?}
)
Because traits indicate shared behavior between data types, they are useful when writing generics.
Further information
在 Rust 中,當你創(chuàng)建一個持有引用的 struct
時赃梧,你需要確保這些引用在 struct
的使用期間保持有效滤蝠。這里的問題在于 Book
這個結(jié)構(gòu)體的字段 author
和 title
是對字符串字面量的引用,但在 main
函數(shù)中槽奕,它們是對 String
類型的引用几睛。由于 String
類型的大小可變,它不能保證其引用的生命周期粤攒,因此我們需要明確地指定生命周期所森。
要修復(fù)這個問題囱持,我們需要為 Book
結(jié)構(gòu)體中的引用添加生命周期注解。這可以通過在結(jié)構(gòu)體定義中為每個引用字段添加生命周期參數(shù)來完成焕济。這里是修復(fù)后的代碼:
struct Book<'a> {
author: &'a str,
title: &'a str,
}
fn main() {
let name = String::from("Jill Smith");
let title = String::from("Fish Flying");
// 必須保證 name 和 title 在 Book 使用期間有效
let book = Book { author: &name, title: &title };
println!("{} by {}", book.title, book.author);
}
在這個修復(fù)版本中纷妆,我們?yōu)?Book
結(jié)構(gòu)體添加了一個生命周期參數(shù) 'a
,并在 author
和 title
字段的引用上使用了這個生命周期參數(shù)晴弃。這意味著 Book
中的引用必須和 'a
生命周期一樣長掩幢。
然而,上面的代碼仍然無法編譯上鞠,因為 main
函數(shù)中的 name
和 title
是 String
類型际邻,而不是 &str
類型。我們需要將它們轉(zhuǎn)換為字符串切片(&str
):
fn main() {
let name = String::from("Jill Smith");
let title = String::from("Fish Flying");
// 轉(zhuǎn)換 String 為 &str 類型的切片
let book = Book {
author: name.as_str(),
title: title.as_str(),
};
println!("{} by {}", book.title, book.author);
}
在這個版本中芍阎,我們使用 as_str
方法將 String
類型轉(zhuǎn)換為 &str
類型的切片世曾,這樣就可以滿足 Book
結(jié)構(gòu)體的要求了。這樣修改后谴咸,代碼應(yīng)該能夠編譯并運行轮听,打印出書名和作者名。
本文由mdnice多平臺發(fā)布