mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-01 08:19:18 +00:00
翻譯
This commit is contained in:
parent
5a7cb8ee1d
commit
ade5ab5600
@ -2,6 +2,8 @@
|
|||||||
//
|
//
|
||||||
// 執行 `rustlings hint clippy2` 或使用 `hint` 子命令來獲取提示。
|
// 執行 `rustlings hint clippy2` 或使用 `hint` 子命令來獲取提示。
|
||||||
|
|
||||||
|
// I AM NOT DONE
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let mut res = 42;
|
let mut res = 42;
|
||||||
let option = Some(12);
|
let option = Some(12);
|
||||||
|
|||||||
@ -3,6 +3,8 @@
|
|||||||
// 這裡有一些簡單的 Clippy 修正,你可以看到它的實用性。
|
// 這裡有一些簡單的 Clippy 修正,你可以看到它的實用性。
|
||||||
// 沒有提示。
|
// 沒有提示。
|
||||||
|
|
||||||
|
// I AM NOT DONE
|
||||||
|
|
||||||
#[allow(unused_variables, unused_assignments)]
|
#[allow(unused_variables, unused_assignments)]
|
||||||
fn main() {
|
fn main() {
|
||||||
let my_option: Option<()> = None;
|
let my_option: Option<()> = None;
|
||||||
|
|||||||
@ -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.
|
Rust 還提供了實現後可用於類型轉換的特徵。這些特徵位於 [`convert`](https://doc.rust-lang.org/std/convert/index.html) 模組下。
|
||||||
The traits are the following:
|
這些特徵包括:
|
||||||
|
|
||||||
- `From` and `Into` covered in [`from_into`](from_into.rs)
|
- `From` 和 `Into` 涵蓋在 [`from_into`](from_into.rs)
|
||||||
- `TryFrom` and `TryInto` covered in [`try_from_into`](try_from_into.rs)
|
- `TryFrom` 和 `TryInto` 涵蓋在 [`try_from_into`](try_from_into.rs)
|
||||||
- `AsRef` and `AsMut` covered in [`as_ref_mut`](as_ref_mut.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)
|
- [conversions](https://doc.rust-lang.org/std/convert/index.html)
|
||||||
- [`FromStr` trait](https://doc.rust-lang.org/std/str/trait.FromStr.html)
|
- [`FromStr` trait](https://doc.rust-lang.org/std/str/trait.FromStr.html)
|
||||||
|
|||||||
@ -20,6 +20,8 @@ impl Default for Person {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// I AM NOT DONE
|
||||||
|
|
||||||
// 你的任務是完成此實現,以便讓 `let p1 = Person::from("Mark,20")` 這行代碼可以編譯。請注意,您需要將年齡部分解析為 `usize`,可以使用 `"4".parse::<usize>()` 之類的方法。需要適當處理此操作的結果。
|
// 你的任務是完成此實現,以便讓 `let p1 = Person::from("Mark,20")` 這行代碼可以編譯。請注意,您需要將年齡部分解析為 `usize`,可以使用 `"4".parse::<usize>()` 之類的方法。需要適當處理此操作的結果。
|
||||||
//
|
//
|
||||||
// 步驟:
|
// 步驟:
|
||||||
|
|||||||
@ -1,13 +1,8 @@
|
|||||||
// from_str.rs
|
// from_str.rs
|
||||||
//
|
//
|
||||||
// This is similar to from_into.rs, but this time we'll implement `FromStr` and
|
// 這與 from_into.rs 類似,但這次我們將實現 `FromStr` 並返回錯誤,而不是回退到默認值。此外,在實現 FromStr 之後,你可以在字串上使用 `parse` 方法來生成實現者類型的物件。可以在 https://doc.rust-lang.org/std/str/trait.FromStr.html 閱讀更多相關資訊。
|
||||||
// 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
|
|
||||||
//
|
//
|
||||||
// Execute `rustlings hint from_str` or use the `hint` watch subcommand for a
|
// 執行 `rustlings hint from_str` 或使用 `hint` 子命令來獲取提示。
|
||||||
// hint.
|
|
||||||
|
|
||||||
use std::num::ParseIntError;
|
use std::num::ParseIntError;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
@ -18,32 +13,29 @@ struct Person {
|
|||||||
age: usize,
|
age: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
// We will use this error type for the `FromStr` implementation.
|
// 我們將使用此錯誤類型來實現 `FromStr`。
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq)]
|
||||||
enum ParsePersonError {
|
enum ParsePersonError {
|
||||||
// Empty input string
|
// 輸入字串為空
|
||||||
Empty,
|
Empty,
|
||||||
// Incorrect number of fields
|
// 字段數量不正確
|
||||||
BadLen,
|
BadLen,
|
||||||
// Empty name field
|
// 名字字段為空
|
||||||
NoName,
|
NoName,
|
||||||
// Wrapped error from parse::<usize>()
|
// 來自 parse::<usize>() 的錯誤
|
||||||
ParseInt(ParseIntError),
|
ParseInt(ParseIntError),
|
||||||
}
|
}
|
||||||
|
|
||||||
// I AM NOT DONE
|
// I AM NOT DONE
|
||||||
|
|
||||||
// Steps:
|
// 步驟:
|
||||||
// 1. If the length of the provided string is 0, an error should be returned
|
// 1. 如果提供的字串長度為 0,則應返回錯誤
|
||||||
// 2. Split the given string on the commas present in it
|
// 2. 將給定的字串按照其中的逗號分割
|
||||||
// 3. Only 2 elements should be returned from the split, otherwise return an
|
// 3. 分割後應返回 2 個元素,否則返回錯誤
|
||||||
// error
|
// 4. 從分割操作中提取第一個元素並用作名字
|
||||||
// 4. Extract the first element from the split operation and use it as the name
|
// 5. 從分割操作中提取另一個元素並將其解析為 `usize` 作為年齡,如 `"4".parse::<usize>()`
|
||||||
// 5. Extract the other element from the split operation and parse it into a
|
// 6. 如果在提取名字和年齡時出現錯誤,應返回錯誤
|
||||||
// `usize` as the age with something like `"4".parse::<usize>()`
|
// 如果一切順利,則返回一個 Person 物件的 Result
|
||||||
// 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
|
|
||||||
|
|
||||||
impl FromStr for Person {
|
impl FromStr for Person {
|
||||||
type Err = ParsePersonError;
|
type Err = ParsePersonError;
|
||||||
|
|||||||
@ -1,13 +1,8 @@
|
|||||||
// try_from_into.rs
|
// try_from_into.rs
|
||||||
//
|
//
|
||||||
// TryFrom is a simple and safe type conversion that may fail in a controlled
|
// TryFrom 是一種簡單且安全的類型轉換,在某些情況下可能會以可控制的方式失敗。基本上,這與 From 類似。主要的區別在於這應該返回一個 Result 類型,而不是目標類型本身。你可以在 https://doc.rust-lang.org/std/convert/trait.TryFrom.html 閱讀更多相關資訊。
|
||||||
// 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
|
|
||||||
//
|
//
|
||||||
// Execute `rustlings hint try_from_into` or use the `hint` watch subcommand for
|
// 執行 `rustlings hint try_from_into` 或使用 `hint` 子命令來獲取提示。
|
||||||
// a hint.
|
|
||||||
|
|
||||||
use std::convert::{TryFrom, TryInto};
|
use std::convert::{TryFrom, TryInto};
|
||||||
|
|
||||||
@ -18,40 +13,35 @@ struct Color {
|
|||||||
blue: u8,
|
blue: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
// We will use this error type for these `TryFrom` conversions.
|
// 我們將使用這個錯誤類型來進行 `TryFrom` 轉換。
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq)]
|
||||||
enum IntoColorError {
|
enum IntoColorError {
|
||||||
// Incorrect length of slice
|
// 切片長度不正確
|
||||||
BadLen,
|
BadLen,
|
||||||
// Integer conversion error
|
// 整數轉換錯誤
|
||||||
IntConversion,
|
IntConversion,
|
||||||
}
|
}
|
||||||
|
|
||||||
// I AM NOT DONE
|
// I AM NOT DONE
|
||||||
|
|
||||||
// Your task is to complete this implementation and return an Ok result of inner
|
// 你的任務是完成此實現並返回內部類型為 Color 的 Ok 結果。你需要為三個整數的元組、三個整數的數組和整數的切片創建實現。
|
||||||
// type Color. You need to create an implementation for a tuple of three
|
// 請注意,元組和數組的實現將在編譯時檢查,但切片實現需要檢查切片的長度!還要注意,正確的 RGB 顏色值必須是範圍在 0..=255 內的整數。
|
||||||
// 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.
|
|
||||||
|
|
||||||
// Tuple implementation
|
// 元組實現
|
||||||
impl TryFrom<(i16, i16, i16)> for Color {
|
impl TryFrom<(i16, i16, i16)> for Color {
|
||||||
type Error = IntoColorError;
|
type Error = IntoColorError;
|
||||||
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
|
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Array implementation
|
// 數組實現
|
||||||
impl TryFrom<[i16; 3]> for Color {
|
impl TryFrom<[i16; 3]> for Color {
|
||||||
type Error = IntoColorError;
|
type Error = IntoColorError;
|
||||||
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
|
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Slice implementation
|
// 切片實現
|
||||||
impl TryFrom<&[i16]> for Color {
|
impl TryFrom<&[i16]> for Color {
|
||||||
type Error = IntoColorError;
|
type Error = IntoColorError;
|
||||||
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
|
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
|
||||||
@ -59,19 +49,19 @@ impl TryFrom<&[i16]> for Color {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
// Use the `try_from` function
|
// 使用 `try_from` 函數
|
||||||
let c1 = Color::try_from((183, 65, 14));
|
let c1 = Color::try_from((183, 65, 14));
|
||||||
println!("{:?}", c1);
|
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();
|
let c2: Result<Color, _> = [183, 65, 14].try_into();
|
||||||
println!("{:?}", c2);
|
println!("{:?}", c2);
|
||||||
|
|
||||||
let v = vec![183, 65, 14];
|
let v = vec![183, 65, 14];
|
||||||
// With slice we should use `try_from` function
|
// 使用切片我們應該使用 `try_from` 函數
|
||||||
let c3 = Color::try_from(&v[..]);
|
let c3 = Color::try_from(&v[..]);
|
||||||
println!("{:?}", c3);
|
println!("{:?}", c3);
|
||||||
// or take slice within round brackets and use TryInto
|
// 或在圓括號內使用切片並使用 TryInto
|
||||||
let c4: Result<Color, _> = (&v[..]).try_into();
|
let c4: Result<Color, _> = (&v[..]).try_into();
|
||||||
println!("{:?}", c4);
|
println!("{:?}", c4);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,14 +1,10 @@
|
|||||||
// using_as.rs
|
// using_as.rs
|
||||||
//
|
//
|
||||||
// Type casting in Rust is done via the usage of the `as` operator. Please note
|
// 在 Rust 中,類型轉換是通過使用 `as` 運算符完成的。請注意,`as` 運算符不僅僅用於類型轉換。它還有助於重命名導入項。
|
||||||
// that the `as` operator is not only used when type casting. It also helps with
|
|
||||||
// renaming imports.
|
|
||||||
//
|
//
|
||||||
// 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
|
// 執行 `rustlings hint using_as` 或使用 `hint` watch 子命令來獲取提示。
|
||||||
// hint.
|
|
||||||
|
|
||||||
// I AM NOT DONE
|
// I AM NOT DONE
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user