I come from a C++ background, and I'm trying to translate one of the programs I wrote back in the days to Rust, primarily for learning purposes.
The problem is this: I need to read some binary data through some library, and I have two cases:
- Data is a string
- Data is anything else (any kind of integer)
In C++, I'd simply specialize a template, which will only give compile-errors if something was not doable/reachable at compile-time; e.g., if I call a function on something that doesn't exist after everything is resolved.
I'm trying to achieve the same in Rust, here's my minimum reproducible example code. It can be found on playground here.
fn main() {
let _x: TheStruct<String> = TheStruct::new();
}
#[warn(dead_code)]
struct TheStruct<T> {
val: T,
}
impl<T> TheStruct<T> {
// so this is a function that is supposed to call two possible implementations if T is a string or T is something else
fn new() -> Self {
// This call is supposed to chooses the impl below based on type
TheStruct::<T>::make_one()
}
}
// this is String impl
impl TheStruct<String> {
fn make_one() -> Self {
TheStruct::<String> {
val: String::new(),
}
}
}
// this is "everything else" impl
impl<T: Default> TheStruct<T> {
fn make_one()-> Self {
TheStruct {
val: T::default()
}
}
}
How can I achieve this in Rust? I'd appreciate helping me to get this to compile.
Also I'd like to point out that some implementations should be the same for both String and other types. I mean: I don't want to specialize everything, i.e., all methods, for String.