本文簡要介紹rust語言中 Trait std::convert::Into 的用法。
用法
pub trait Into<T> {
fn into(self) -> T;
}消耗輸入值的value-to-value 轉換。與 From 相反。
應該避免實施 Into ,而是實施 From 。由於標準庫中的一攬子實現,實現 From 會自動提供 Into 的實現。
在指定泛型函數的 trait bound 時,優先使用 Into 而不是 From ,以確保也可以使用僅實現 Into 的類型。
注意:這個特質一定不能失敗.如果轉換可能失敗,請使用TryInto.
通用實現
在舊版本的 Rust 中實現Into 以轉換為外部類型
在 Rust 1.41 之前,如果目標類型不是當前 crate 的一部分,那麽你不能直接實現 From 。例如,使用以下代碼:
struct Wrapper<T>(Vec<T>);
impl<T> From<Wrapper<T>> for Vec<T> {
fn from(w: Wrapper<T>) -> Vec<T> {
w.0
}
}這將無法在舊版本的語言中編譯,因為 Rust 的孤兒規則曾經更嚴格一些。為了繞過這個,你可以直接實現 Into :
struct Wrapper<T>(Vec<T>);
impl<T> Into<Vec<T>> for Wrapper<T> {
fn into(self) -> Vec<T> {
self.0
}
}重要的是要了解 Into 不提供 From 實現(就像 From 與 Into 一樣)。因此,您應始終嘗試實施 From ,如果無法實施 From ,則回退到 Into 。
例子
String 實現 Into < Vec < u8 >> :
為了表達我們希望泛型函數采用可以轉換為指定類型 T 的所有參數,我們可以使用 Into <T> 的特征邊界。例如:函數 is_hello 接受所有可以轉換為 Vec < u8 > 的參數。
fn is_hello<T: Into<Vec<u8>>>(s: T) {
let bytes = b"hello".to_vec();
assert_eq!(bytes, s.into());
}
let s = "hello".to_string();
is_hello(s);相關用法
- Rust IntoKeys用法及代碼示例
- Rust IntoIter.as_mut_slice用法及代碼示例
- Rust IntoInnerError.error用法及代碼示例
- Rust IntoIter.new用法及代碼示例
- Rust IntoValues用法及代碼示例
- Rust IntoIterator.into_iter用法及代碼示例
- Rust IntoInnerError.into_inner用法及代碼示例
- Rust IntoInnerError.into_parts用法及代碼示例
- Rust IntoIter.as_slice用法及代碼示例
- Rust IntoIterator用法及代碼示例
- Rust IntoIter用法及代碼示例
- Rust IntoRawFd.into_raw_fd用法及代碼示例
- Rust IntoInnerError.into_error用法及代碼示例
- Rust IntoInnerError用法及代碼示例
- Rust IntErrorKind用法及代碼示例
- Rust Intersection用法及代碼示例
- Rust Infallible用法及代碼示例
- Rust Incoming用法及代碼示例
- Rust Instant.checked_duration_since用法及代碼示例
- Rust Index用法及代碼示例
- Rust Instant.now用法及代碼示例
- Rust Instant.saturating_duration_since用法及代碼示例
- Rust Instant.duration_since用法及代碼示例
- Rust Instant用法及代碼示例
- Rust IndexMut用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Trait std::convert::Into。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
