Mel*_*vin 1 generics self rust type-annotation
我的函数是结构的一部分(出于上下文原因),它不接受参数self。此外,结构本身采用T带有一些特征限制的通用参数:
trait SomeRestriction {}
struct SomeStruct<T: SomeRestriction>(T);
impl<T: SomeRestriction> SomeStruct<T> {
fn some_function_that_does_not_take_self() -> String {
todo!()
}
}
Run Code Online (Sandbox Code Playgroud)
我想编写一个测试,并且想避免为该函数提供self参数,因为使用一些通用结构参数模拟对象对于该小函数和测试来说需要付出很大的努力。
我在其他测试中这样做,因为那里有必要,但我想尽可能避免它。
我尝试这样称呼它:
let some_string = SomeStruct::some_function_that_does_not_take_self();
Run Code Online (Sandbox Code Playgroud)
但它会要求我提供类型注释,即使不需要。
有没有办法在不模拟结构或从结构实现中删除函数的情况下调用它?
有没有办法在不模拟结构或从结构实现中删除函数的情况下调用它?
不。据 Rust 所知SomeStruct<T>::some_function_that_does_not_take_self,每个T. 他们也可能有不同的行为,考虑一下:
use core::fmt::Debug;
#[derive(Debug, Default)] struct A;
#[derive(Debug, Default)] struct B;
struct C<T> { t: T }
impl<T: Debug + Default> C<T> {
fn foo() { println!("{:?}", T::default()) }
}
fn main() {
C::<A>::foo(); // Prints 'A'.
C::<B>::foo(); // Prints 'B'.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1296 次 |
| 最近记录: |