yax*_*aks 1 c++ generics templates rust
以下 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法:
trait Newable{
fn new() -> Self;
}
fn stuff<T: Newable>() -> T {
T::new()
}
Run Code Online (Sandbox Code Playgroud)
我尝试为此使用新类型 -
struct NwVec<T>{
vec: Vec<T>
}
impl<T> Newable<T> for NwVec<T>{
fn new() -> Self {
NwVec { vec: Vec::new() }
}
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
fn main() {
let x: NwVec<i32> = stuff::<NwVec<i32>>();
}
Run Code Online (Sandbox Code Playgroud)
但我得到一个
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`
Run Code Online (Sandbox Code Playgroud)
有没有办法实现C++程序所达到的效果?
PS:我对 Rust 还很陌生,如果这个问题的解决方案很微不足道,我真的很抱歉。
当您输入您所说的给您提供的错误的代码时,可能存在混淆,因为当我尝试时,相同的代码没有产生该特定错误。
不管怎样,你已经很接近了。考虑这段代码:
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:?}");
}
Run Code Online (Sandbox Code Playgroud)
我改变的只是:
#[derive(Debug)]到NwVec<T>以便我们可以打印出来<T>从Newable<T>你原来的impl<T> Newable<T> for NwVec<T>. 这是因为Newable您的帖子中提供的特征本身不是通用的,因此它不需要类型参数。我想这是一个学习练习,但如果您很好奇,您可能会对std::default::Default其中的一个特征感兴趣Newable,因为它的实现提供了一种简单且一致的方式来创建某些内容的“默认”版本。Vec它本身是一个实现者,因此您可以在需要a 的任何地方调用 egDefault::default()或 a 。检查一下这个游乐场。Vec::default()Vec<T>