I started off with a function a bit like this (playground):
fn find <T: Copy> (src: &[T], index: usize) -> T {
// more complex algorithm, involving src goes here
src[index]
}
pub fn main() {
let x = b"abc";
assert_eq!(b'b', find(x, 1));
}
And I wanted to generalise it so that I can use any appropriate type for src
. The best I came up with is this (playground):
trait RandomAccess<T> {
fn get_at(&self, index: usize) -> T;
}
impl <T: Copy> RandomAccess<T> for [T] {
fn get_at(&self, index: usize) -> T {
self[index]
}
}
fn find <T: Copy, S: ?Sized + RandomAccess<T>> (src: &S, index: usize) -> T {
// more complex algorithm, involving src goes here
src.get_at(index)
}
pub fn main() {
let x = b"xyz";
assert_eq!(b'y', find(&x[..], 1));
}
However, I now can't just invoke find(x, 1)
, I have to create a slice: find(&x[..], 1)
.
Is there a way to make this generic, but still be able to invoke find
as in the original example?