gpt4 book ai didi

rust - Rust:通过工厂方法创建结构时出现问题

转载 作者:行者123 更新时间:2023-12-03 11:44:27 25 4
gpt4 key购买 nike

采取这个最小的repro(playground),在这里我尝试将带有闭包的结构作为字段,并定义一些其他工厂方法,以闭包的形式提供自定义逻辑。

#![allow(non_snake_case)]

struct FunStruct<T>
where
T: Fn(i32) -> i32
{
pub p: T,
}

fn Create<T>() -> FunStruct<T>
where
T: Fn(i32) -> i32
{
let p : T = |val| -> i32 {
return val;
};

let a = FunStruct {
p,
};

return a;
}

fn main() {
let a = Create();

println!("{}", (a.p)(5));
}
上面的代码段引发以下错误。
error[E0308]: mismatched types
--> src/main.rs:14:17
|
10 | fn Create<T>() -> FunStruct<T>
| - this type parameter
...
14 | let p : T = |val| -> i32 {
| _____________-___^
| | |
| | expected due to this
15 | | return val;
16 | | };
| |_____^ expected type parameter `T`, found closure
|
= note: expected type parameter `T`
found closure `[closure@src/main.rs:14:17: 16:6]`

error[E0282]: type annotations needed for `FunStruct<T>`
--> src/main.rs:26:13
|
26 | let a = Create();
| - ^^^^^^ cannot infer type for type parameter `T` declared on the function `Create`
| |
| consider giving `a` the explicit type `FunStruct<T>`, where the type parameter `T` is specified
|
= note: type must be known at this point

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0282, E0308.
For more information about an error, try `rustc --explain E0282`.
但是,这似乎很好
struct FunStruct<T>
where
T: Fn(i32) -> i32
{
pub p: T,
}

fn main() {
let p = |val| -> i32 {
return val;
};

let a = FunStruct {
p
};

println!("{}", (a.p)(5));
}
某种程度的抽象似乎毁了它。

最佳答案

通用参数意味着它适用于任何类型-但是,Create中的闭包不适用于任何闭包类型,它会创建具有一个特定类型的闭包。你可以这样做:

fn Create() -> FunStruct<impl Fn(i32) -> i32>{
let p/*: some anonymous, unique type */ = |val| -> i32 {
return val;
};

let a = FunStruct {
p,
};

return a;
}
返回位置中的 impl Trait表示“我返回实现此特征的某种类型,虽然我不会告诉您它实际上是什么”。相反,您的原始函数说“给定一个函数的任何类型,我都可以返回它”-这显然没有意义。

关于rust - Rust:通过工厂方法创建结构时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64620035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com