How to use genertic type with commond? #9554
-
I'm trying write a command like this to get properties in state. #[tauri::command]
pub async fn do_something<T>(name: String, data: T, state: tauri::State<'_, MyState>) -> Result<T, ()> {
let mut guard = state.0.lock().await;
match name.as_str() {
"case1" => {
return Ok(guard.property1.clone());
},
"case2" => {
return Ok(guard.property2.clone());
},
_ => {
println!("no match");
}
}
Err(())
} But the compiler errors cannot find type `T` in this scope
not found in this scope It's ok to declare a combines type in ts like this, but it seems we can not do it in rust interface Apple { coloe: string }
interface Car { life: number }
type CombinedAndType = Car & Apple;
type CombinedOrType = Car | Apple; So how can i use genertic type with tauri command? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Yeah, this is indeed not possible. Rust needs to know the actual type behind the generic at compile time. If you just want something working quickly you can use serde_json::Value which is basically a dynamic object. Then you'll have to do the type checking at runtime yourself (checking the object properties). |
Beta Was this translation helpful? Give feedback.
Yeah, this is indeed not possible. Rust needs to know the actual type behind the generic at compile time.
So in rust you'd need a trait and have multiple structs that implement that trait and resemble your ts types.Without generics you can also just use an enum with the different fields (must implement serde::Deserialize correctly).Edit: Now that i think about it, iirc tauri::commands don't support generics at all.
If you just want something working quickly you can use serde_json::Value which is basically a dynamic object. Then you'll have to do the type checking at runtime yourself (checking the object properties).