我想调用为&[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 的行修改为没有编译错误?
答案 0 :(得分:3)
<&[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);
}