How to map data in Rust?

I am trying to match the data type of a common field structure and respond accordingly. My general idea was this (code does not compile):

struct foo<T> { zaz: String, bar: T, } fn main() { let x = foo::<String> { zaz: "Hello".to_string(), bar: "world".to_string(), }; let y = foo::<u32> { zaz: "Hello".to_string(), bar: 5, }; match x.bar { String => println!("It a string!"), u32 => println!("It a u32!"), _ => println!("Something else"), }; println!("end of program!"); } 

Error message from rustc :

 error[E0001]: unreachable pattern --> src/main.rs:18:9 | 18 | u32 => println!("It a u32!"), | ^^^ this is an unreachable pattern | note: this pattern matches any value --> src/main.rs:17:9 | 17 | String => println!("It a string!"), | ^^^^^^ error[E0001]: unreachable pattern --> src/main.rs:19:9 | 19 | _ => println!("Something else"), | ^ this is an unreachable pattern | note: this pattern matches any value --> src/main.rs:17:9 | 17 | String => println!("It a string!"), | ^^^^^^ 

I wanted x match the first and y to the second. Actually, I’m not sure what I want to do, but to achieve the desired effect?

+6
source share
1 answer

Idiomatic solution

Create a sign that restricts the parameter T to foo , implements any specific behavior as a related function of this sign.

Example:

 trait PrintMe { fn print_me(&self); } impl PrintMe for String { fn print_me(&self) { println!("I am a string"); } } struct Foo<T: PrintMe> { zaz: String, bar: T } fn main() { // ... x.bar.print_me(); } 

This is a fundamental general programming, where you precisely determine the difference in the behavior of possible common parameters, so there is nothing surprising.


Exact solution

Rust can indeed request types: each type has a unique TypeId , and you can map TypeId to an if series. This is awkward.

 fn print_me<T>(x: &Foo<T>) { if TypeId::of::<T>() == TypeId::of::<String>() { println!("I am a string"); } else // ... } 

But please ... don't do this :)

+8
source

Source: https://habr.com/ru/post/1013994/


All Articles