[英]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.