如何显式调用片的方法不使用的typedef?(How do I explicitly call a

2019-09-27 17:34发布

我想调用为类型实现的方法&[i32] 我可以通过类型别名做得一样所示的线标记为1,但有可能在不引入每次一个类型别名?

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
}

标记2的线产生的错误消息:

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

是否有可能修改线条为标志2没有编译错误?

Answer 1:

使用完全合格的语法 :

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

不是一个方法,顺便说一句。 一种方法采用self以某种形式。 这仅仅是一个相关的功能 。 如果这一个方法,你可以称它像任何其他方法:

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);
}


文章来源: How do I explicitly call a method on a slice without using a typedef?
标签: rust