user1244932
user1244932

Reputation: 8142

How do I explicitly call a method on a slice without using a typedef?

I want to call a method that is implemented for the type &[i32]. I can do it via type alias as shown on line marked 1, but is it possible without introducing a type alias every time?

trait Foo<T> {
    fn say_hi(x: T);
}

impl<'a> Foo<i32> for &'a [i32] {
    fn say_hi(x: i32) {}
}

type Array<'a> = &'a [i32];

fn main() {
    let arr = [1, 2, 3];
    Array::say_hi(1);//line 1
    &[i32]::say_hi(1);//line 2
}

The line marked 2 produces an error message:

error: expected one of `.`, `;`, `?`, `}`, or an operator, found `::`
  --> /home/xxx/.emacs.d/rust-playground/at-2017-08-09-051114/snippet.rs:21:11
   |
21 |     &[i32]::say_hi(1);
   |           ^^ expected one of `.`, `;`, `?`, `}`, or an operator here

error[E0423]: expected value, found builtin type `i32`
  --> /home/xxx/.emacs.d/rust-playground/at-2017-08-09-051114/snippet.rs:21:7
   |
21 |     &[i32]::say_hi(1);
   |       ^^^ not a value

Is it possible to modify the line marked 2 to not have a compilation error?

Upvotes: 1

Views: 240

Answers (1)

Shepmaster
Shepmaster

Reputation: 431669

Use the Fully Qualified Syntax:

<&[i32]>::say_hi(1);

This is not a method, by the way. A method takes self in some form. This is just an associated function. If it was a method, you could just call it like any other method:

trait Foo<T> {
    fn say_hi(&self, x: T);
}

impl Foo<i32> for [i32] {
    fn say_hi(&self, x: i32) {}
}

fn main() {
    let arr = [1, 2, 3];
    <[i32]>::say_hi(&arr, 1);
    arr.say_hi(1);
}

Upvotes: 5

Related Questions