如何在不提供泛型类型的情况下调用泛型类型上的关联函数?

问题描述

我有一个不采用 self 参数的结构(出于上下文原因)的一部分的函数。此外,结构本身采用具有一些特征限制的通用参数 T

trait SomeRestriction {}
struct SomeStruct<T: SomeRestriction>(T);

impl<T: SomeRestriction> SomeStruct<T> {
    fn some_function_that_does_not_take_self() -> String {
        todo!()
    }
}

我想写一个测试,我想避免给 该函数 self 参数,因为模拟对象 对于那个小函数和测试来说,使用一些通用的结构参数需要付出很多努力。

我在其他测试中这样做,因为那里有必要,但我想尽可能避免它。

我试着这样称呼它:

let some_string = SomeStruct::some_function_that_does_not_take_self();

但它会要求我提供类型注释,即使它不需要。

有没有办法在不模拟结构或从结构实现中删除函数的情况下调用它?

解决方法

有没有办法在不模拟结构或从结构实现中删除函数的情况下调用它?

没有。 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'.
}
,

orlp said:否,您必须提供具体类型。

为那个小功能和测试付出了很多努力

对于您的具体示例,您可以编写不同的代码,以便通过删除不需要的特征边界来更容易地提供具体类型:

trait SomeRestriction {}
struct SomeStruct<T>(T);

impl<T> SomeStruct<T> {
    fn some_function_that_does_not_take_self() -> String { todo!() }
}

impl<T: SomeRestriction> SomeStruct<T> {
    // functions that actually use `T`
}

fn main() {
    let some_string = SomeStruct::<()>::some_function_that_does_not_take_self();
}

另见:

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...