This commit is contained in:
TimLai666 2024-06-19 14:11:52 +08:00 committed by GitHub
parent 5a7cb8ee1d
commit ade5ab5600
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 50 additions and 66 deletions

View File

@ -2,6 +2,8 @@
//
// 執行 `rustlings hint clippy2` 或使用 `hint` 子命令來獲取提示。
// I AM NOT DONE
fn main() {
let mut res = 42;
let option = Some(12);

View File

@ -3,6 +3,8 @@
// 這裡有一些簡單的 Clippy 修正,你可以看到它的實用性。
// 沒有提示。
// I AM NOT DONE
#[allow(unused_variables, unused_assignments)]
fn main() {
let my_option: Option<()> = None;

View File

@ -1,23 +1,23 @@
# Type conversions
# 類型轉換
Rust offers a multitude of ways to convert a value of a given type into another type.
Rust 提供了多種將某一類型的值轉換為另一類型的方法。
The simplest form of type conversion is a type cast expression. It is denoted with the binary operator `as`. For instance, `println!("{}", 1 + 1.0);` would not compile, since `1` is an integer while `1.0` is a float. However, `println!("{}", 1 as f32 + 1.0)` should compile. The exercise [`using_as`](using_as.rs) tries to cover this.
最簡單的類型轉換形式是類型轉換表達式。它由二元運算符 `as` 表示。例如,`println!("{}", 1 + 1.0);` 這段程式碼不會編譯,因為 `1` 是整數,而 `1.0` 是浮點數。但是,`println!("{}", 1 as f32 + 1.0)` 則可以編譯。練習 [`using_as`](using_as.rs) 涵蓋了這部分內容。
Rust also offers traits that facilitate type conversions upon implementation. These traits can be found under the [`convert`](https://doc.rust-lang.org/std/convert/index.html) module.
The traits are the following:
Rust 還提供了實現後可用於類型轉換的特徵。這些特徵位於 [`convert`](https://doc.rust-lang.org/std/convert/index.html) 模組下。
這些特徵包括:
- `From` and `Into` covered in [`from_into`](from_into.rs)
- `TryFrom` and `TryInto` covered in [`try_from_into`](try_from_into.rs)
- `AsRef` and `AsMut` covered in [`as_ref_mut`](as_ref_mut.rs)
- `From` `Into` 涵蓋在 [`from_into`](from_into.rs)
- `TryFrom` `TryInto` 涵蓋在 [`try_from_into`](try_from_into.rs)
- `AsRef` `AsMut` 涵蓋在 [`as_ref_mut`](as_ref_mut.rs)
Furthermore, the `std::str` module offers a trait called [`FromStr`](https://doc.rust-lang.org/std/str/trait.FromStr.html) which helps with converting strings into target types via the `parse` method on strings. If properly implemented for a given type `Person`, then `let p: Person = "Mark,20".parse().unwrap()` should both compile and run without panicking.
此外,`std::str` 模塊提供了一個名為 [`FromStr`](https://doc.rust-lang.org/std/str/trait.FromStr.html) 的特徵,這個特徵通過字串上的 `parse` 方法幫助將字串轉換為目標類型。如果對於給定類型 `Person` 正確實現了此特徵,那麼 `let p: Person = "Mark,20".parse().unwrap()` 不僅應該編譯,還應該在運行時不會恐慌。
These should be the main ways ***within the standard library*** to convert data into your desired types.
這些應該是標準庫中將數據轉換為所需類型的主要方法。
## Further information
## 進一步了解
These are not directly covered in the book, but the standard library has a great documentation for it.
這些內容沒有在書中直接涵蓋,但標準庫有詳細的文件說明。
- [conversions](https://doc.rust-lang.org/std/convert/index.html)
- [`FromStr` trait](https://doc.rust-lang.org/std/str/trait.FromStr.html)

View File

@ -20,6 +20,8 @@ impl Default for Person {
}
}
// I AM NOT DONE
// 你的任務是完成此實現,以便讓 `let p1 = Person::from("Mark,20")` 這行代碼可以編譯。請注意,您需要將年齡部分解析為 `usize`,可以使用 `"4".parse::<usize>()` 之類的方法。需要適當處理此操作的結果。
//
// 步驟:

View File

@ -1,13 +1,8 @@
// from_str.rs
//
// This is similar to from_into.rs, but this time we'll implement `FromStr` and
// return errors instead of falling back to a default value. Additionally, upon
// implementing FromStr, you can use the `parse` method on strings to generate
// an object of the implementor type. You can read more about it at
// https://doc.rust-lang.org/std/str/trait.FromStr.html
// 這與 from_into.rs 類似,但這次我們將實現 `FromStr` 並返回錯誤,而不是回退到默認值。此外,在實現 FromStr 之後,你可以在字串上使用 `parse` 方法來生成實現者類型的物件。可以在 https://doc.rust-lang.org/std/str/trait.FromStr.html 閱讀更多相關資訊。
//
// Execute `rustlings hint from_str` or use the `hint` watch subcommand for a
// hint.
// 執行 `rustlings hint from_str` 或使用 `hint` 子命令來獲取提示。
use std::num::ParseIntError;
use std::str::FromStr;
@ -18,32 +13,29 @@ struct Person {
age: usize,
}
// We will use this error type for the `FromStr` implementation.
// 我們將使用此錯誤類型來實現 `FromStr`。
#[derive(Debug, PartialEq)]
enum ParsePersonError {
// Empty input string
// 輸入字串為空
Empty,
// Incorrect number of fields
// 字段數量不正確
BadLen,
// Empty name field
// 名字字段為空
NoName,
// Wrapped error from parse::<usize>()
// 來自 parse::<usize>() 的錯誤
ParseInt(ParseIntError),
}
// I AM NOT DONE
// Steps:
// 1. If the length of the provided string is 0, an error should be returned
// 2. Split the given string on the commas present in it
// 3. Only 2 elements should be returned from the split, otherwise return an
// error
// 4. Extract the first element from the split operation and use it as the name
// 5. Extract the other element from the split operation and parse it into a
// `usize` as the age with something like `"4".parse::<usize>()`
// 6. If while extracting the name and the age something goes wrong, an error
// should be returned
// If everything goes well, then return a Result of a Person object
// 步驟:
// 1. 如果提供的字串長度為 0則應返回錯誤
// 2. 將給定的字串按照其中的逗號分割
// 3. 分割後應返回 2 個元素,否則返回錯誤
// 4. 從分割操作中提取第一個元素並用作名字
// 5. 從分割操作中提取另一個元素並將其解析為 `usize` 作為年齡,如 `"4".parse::<usize>()`
// 6. 如果在提取名字和年齡時出現錯誤,應返回錯誤
// 如果一切順利,則返回一個 Person 物件的 Result
impl FromStr for Person {
type Err = ParsePersonError;

View File

@ -1,13 +1,8 @@
// try_from_into.rs
//
// TryFrom is a simple and safe type conversion that may fail in a controlled
// way under some circumstances. Basically, this is the same as From. The main
// difference is that this should return a Result type instead of the target
// type itself. You can read more about it at
// https://doc.rust-lang.org/std/convert/trait.TryFrom.html
// TryFrom 是一種簡單且安全的類型轉換,在某些情況下可能會以可控制的方式失敗。基本上,這與 From 類似。主要的區別在於這應該返回一個 Result 類型,而不是目標類型本身。你可以在 https://doc.rust-lang.org/std/convert/trait.TryFrom.html 閱讀更多相關資訊。
//
// Execute `rustlings hint try_from_into` or use the `hint` watch subcommand for
// a hint.
// 執行 `rustlings hint try_from_into` 或使用 `hint` 子命令來獲取提示。
use std::convert::{TryFrom, TryInto};
@ -18,40 +13,35 @@ struct Color {
blue: u8,
}
// We will use this error type for these `TryFrom` conversions.
// 我們將使用這個錯誤類型來進行 `TryFrom` 轉換。
#[derive(Debug, PartialEq)]
enum IntoColorError {
// Incorrect length of slice
// 切片長度不正確
BadLen,
// Integer conversion error
// 整數轉換錯誤
IntConversion,
}
// I AM NOT DONE
// Your task is to complete this implementation and return an Ok result of inner
// type Color. You need to create an implementation for a tuple of three
// integers, an array of three integers, and a slice of integers.
//
// Note that the implementation for tuple and array will be checked at compile
// time, but the slice implementation needs to check the slice length! Also note
// that correct RGB color values must be integers in the 0..=255 range.
// 你的任務是完成此實現並返回內部類型為 Color 的 Ok 結果。你需要為三個整數的元組、三個整數的數組和整數的切片創建實現。
// 請注意,元組和數組的實現將在編譯時檢查,但切片實現需要檢查切片的長度!還要注意,正確的 RGB 顏色值必須是範圍在 0..=255 內的整數。
// Tuple implementation
// 元組實現
impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
}
}
// Array implementation
// 數組實現
impl TryFrom<[i16; 3]> for Color {
type Error = IntoColorError;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
}
}
// Slice implementation
// 切片實現
impl TryFrom<&[i16]> for Color {
type Error = IntoColorError;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
@ -59,19 +49,19 @@ impl TryFrom<&[i16]> for Color {
}
fn main() {
// Use the `try_from` function
// 使用 `try_from` 函數
let c1 = Color::try_from((183, 65, 14));
println!("{:?}", c1);
// Since TryFrom is implemented for Color, we should be able to use TryInto
// 由於 Color 實現了 TryFrom我們應該能夠使用 TryInto
let c2: Result<Color, _> = [183, 65, 14].try_into();
println!("{:?}", c2);
let v = vec![183, 65, 14];
// With slice we should use `try_from` function
// 使用切片我們應該使用 `try_from` 函數
let c3 = Color::try_from(&v[..]);
println!("{:?}", c3);
// or take slice within round brackets and use TryInto
// 或在圓括號內使用切片並使用 TryInto
let c4: Result<Color, _> = (&v[..]).try_into();
println!("{:?}", c4);
}

View File

@ -1,14 +1,10 @@
// using_as.rs
//
// Type casting in Rust is done via the usage of the `as` operator. Please note
// that the `as` operator is not only used when type casting. It also helps with
// renaming imports.
// 在 Rust 中,類型轉換是通過使用 `as` 運算符完成的。請注意,`as` 運算符不僅僅用於類型轉換。它還有助於重命名導入項。
//
// The goal is to make sure that the division does not fail to compile and
// returns the proper type.
// 目標是確保除法不會失敗並返回正確的類型。
//
// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a
// hint.
// 執行 `rustlings hint using_as` 或使用 `hint` watch 子命令來獲取提示。
// I AM NOT DONE