我如何在 Rust 中實作一個泛型函式,以一種可以將泛型型別T(u16、、u32或u64)轉換為Vec<u8>使用小端或大端格式的方式。
例如(無效的 Rust 代碼):
fn convert<T>(a: T) -> vec<u8> {
// a = 0x01234567
// returns vec![0x01, 0x23, 0x45, 0x67]
}
uj5u.com熱心網友回復:
正如@PitaJ 建議實作一個特征可以解決這個問題,這里是一個作業示例:
trait IntoBytes: Sized {
fn to_le_bytes(a: Self) -> Vec<u8>;
}
impl IntoBytes for u16 {
fn to_le_bytes(a: Self) -> Vec<u8> {
a.to_le_bytes().to_vec()
}
}
impl IntoBytes for u32 {
fn to_le_bytes(a: Self) -> Vec<u8> {
a.to_le_bytes().to_vec()
}
}
impl IntoBytes for u64 {
fn to_le_bytes(a: Self) -> Vec<u8> {
a.to_le_bytes().to_vec()
}
}
fn foo<T: IntoBytes>(a: T) -> Vec<u8> {
T::to_le_bytes(a)
}
fn main() {
println!("{:?}", foo::<u32>(87u32));
println!("{:?}", foo::<u64>(0x0123456789abcdfu64));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/495755.html
上一篇:如何回傳一個空的引數化類Box?
