dakom
June 21, 2019, 4:28am
1
Consider the following Playground :
It fails due to conflicting impls. Is there a way to achieve this? i.e. specific impls for different types of slices/vecs/arrays?
struct Foo<T>(T);
trait FooImpl {
fn do_it(&self);
}
impl <T: AsRef<[u8]>> FooImpl for Foo<T> {
fn do_it(&self) {
println!("I am a u8!");
}
}
impl <T: AsRef<[f32]>> FooImpl for Foo<T> {
fn do_it(&self) {
println!("I am a f32!");
}
}
fn main() {
Foo([42u8]).do_it();
Foo(&[42u8]).do_it();
Foo(vec![42u8]).do_it();
Foo(&vec![42u8]).do_it();
Foo([42.0f32]).do_it();
Foo(&[42.0f32]).do_it();
Foo(vec![42.0f32]).do_it();
Foo(&vec![42.0f32]).do_it();
}
dakom
June 21, 2019, 4:32am
2
leudz
June 21, 2019, 4:48am
3
You can use @Nemo157 's solution from the thread you linked and do something like this .
2 Likes
dakom
June 21, 2019, 4:51am
4
Ah - thanks... where I was stuck toying with that was not seeing where PhantomData comes from... didn't think to add a new()
. Much appreciated!
leudz
June 21, 2019, 5:05am
5
You can still make Foo without using new:
Foo([42u8], PhantomData)
but I like it better with it =)
1 Like
dakom
June 21, 2019, 5:08am
6
Btw, off-topic but I'm using your BeachMap a lot... it's great!
dakom
June 21, 2019, 5:20am
7
Followup question... now, when I try an add a function that accepts a FooImpl
like this , it breaks:
fn do_foo<T: FooImpl> (foo:T) {
foo.do_it();
}
FooImpl is only implemented for Foo, guess it should be like this:
do_foo(Foo::new([42u8]));
1 Like
dakom
June 21, 2019, 5:26am
9
d'oh - silly mistake... guess I should have breakfast first thanks!
dakom
June 21, 2019, 5:35am
10
One more gotcha - if I have arrays that are larger than 32, is this the idiomatic way to get around it?
Foo::new(&[42u8;33][..]).do_it();
leudz
June 21, 2019, 5:59am
11
It's the usual way to go about it, you can use this too:
Foo::new([42u8;33].as_ref()).do_it();
1 Like
dakom
June 21, 2019, 6:10am
12
OK and... I think this is the last question for now... if I want to know something about the data on Foo, from within the function that accepts it as a generic Trait, I'll need to make accessor methods part of the trait, right?
Example: Rust Playground
system
Closed
September 19, 2019, 7:58am
14
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.