![](/img/trans.png)
[英]What is the proper way to create new instance of generic class in kotlin?
[英]What is the proper way to create a new generic struct?
我正在尝试创建一个可以初始化为T
类型的通用结构。 它看起来像这样:
pub struct MyStruct<T> {
test_field: Option<T>,
name: String,
age: i32,
}
impl MyStruct<T> {
fn new(new_age: i32, new_name: String) -> MyStruct<T> {
MyStruct<T> {
test_field: None,
age: new_age,
name: new_name,
}
}
}
这似乎不起作用。 在其他错误中,我得到:
error: chained comparison operators require parentheses
--> src/lib.rs:9:17
|
9 | MyStruct<T> {
| ^^^^^
|
我强烈推荐阅读Rust编程语言 。 它涵盖了这样的基础知识,Rust团队花了很多时间来做好事! 具体来说, 关于泛型的部分可能在这里有所帮助。
在实例化结构时,您不需要使用<T>
。 将推断出T
的类型。 您需要声明T
是impl
块上的泛型类型:
struct MyStruct<T> {
test_field: Option<T>,
name: String,
age: i32,
}
impl<T> MyStruct<T> {
// ^^^
fn new(new_age: i32, new_name: String) -> MyStruct<T> {
MyStruct {
test_field: None,
age: new_age,
name: new_name,
}
}
}
作为DK。 指出 ,您可以选择使用turbofish语法( ::<>
)指定类型参数:
MyStruct::<T> {
// ^^^^^
test_field: None,
age: new_age,
name: new_name,
}
现代编译器版本实际上现在告诉你:
= help: use `::<...>` instead of `<...>` if you meant to specify type arguments
= help: or use `(...)` if you meant to specify fn arguments
当类型不明确时,我只见过这样的东西,这种情况并不经常发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.