rust 中的以下 C 程式等價于什么?
#include <iostream>
#include <vector>
template <typename T>
T stuff() {
return T();
}
int main() {
std::vector<int> vec = stuff<std::vector<int>>();
vec.push_back(1);
for (auto &&i : vec) {
std::cout << i << std::endl;
}
}
我嘗試了以下方法:
trait Newable{
fn new() -> Self;
}
fn stuff<T: Newable>() -> T {
T::new()
}
我嘗試為此使用新型別-
struct NwVec<T>{
vec: Vec<T>
}
impl<T> Newable<T> for NwVec<T>{
fn new() -> Self {
NwVec { vec: Vec::new() }
}
}
并像這樣使用它:
fn main() {
let x: NwVec<i32> = stuff::<NwVec<i32>>();
}
但我得到一個
error[E0277]: the trait bound `NwVec<i32>: Newable<NwVec<i32>>` is not satisfied
--> src\main.rs:2:25
|
2 | let x: NwVec<i32> = stuff();
| ^^^^^ the trait `Newable<NwVec<i32>>` is not implemented for `NwVec<i32>`
|
= help: the following implementations were found:
<NwVec<T> as Newable<T>>
note: required by a bound in `stuff`
有沒有辦法實作 C 程式實作的目標?
PS:我對生銹很陌生,如果解決這個問題很簡單,我真的很抱歉。
uj5u.com熱心網友回復:
當您輸入您所說的給您提供的錯誤的代碼時,可能有一個混淆,因為當我嘗試它時,相同的代碼沒有產生那個特定的錯誤。
不管怎樣,你已經很接近了。考慮這段代碼:
trait Newable {
fn new() -> Self;
}
fn stuff<T: Newable>() -> T {
T::new()
}
#[derive(Debug)]
struct NwVec<T> {
vec: Vec<T>
}
impl<T> Newable for NwVec<T> {
fn new() -> Self {
NwVec { vec: Vec::new() }
}
}
fn main() {
let x: NwVec<i32> = stuff::<NwVec<i32>>();
println!("{x:?}");
}
操場
我改變的只是:
- 添加
#[derive(Debug)]
到NwVec<T>
所以我們可以列印出來 - 我從您原來
<T>
的. 這是因為您的帖子中提供的特征本身不是通用的,因此它不需要型別引數。Newable<T>
impl<T> Newable<T> for NwVec<T>
Newable
我想這是一種學習練習,但如果你好奇,你可能會對std::default::Default
哪個特征有點類似于你的特征感興趣,Newable
因為實作提供了一種簡單且一致的方式來創建某事物的“默認”版本。Vec
它本身是一個實作者,因此您可以呼叫 egDefault::default()
或Vec::default()
任何Vec<T>
預期的 a 。檢查這個游樂場。
uj5u.com熱心網友回復:
除了@JorgeIsraelPe?a 的出色回答外,如果您堅持使用Newable
,則不需要新型別。只要特征或型別是您的,您就可以為型別實作特征(嗯,實際規則要復雜一些)。這意味著您可以Newable
直接實作Vec
:
impl<T> Newable for Vec<T> {
fn new() -> Self {
Vec::new()
}
}
fn main() {
let x = stuff::<Vec<i32>>();
println!("{x:?}");
}
游樂場。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470397.html
下一篇:通用特征系結的終身問題