[英]Trait or method that does not depend on generic type
I have a generic structure in rust that has one general field, in this case val and a type specific field:我在 rust 中有一个通用结构,它有一个通用字段,在本例中为val和一个类型特定字段:
struct A<T> {
val: i32,
t: T
}
What I am trying to do is to have a method associated to the struct regardless the type T .我想要做的是让一个方法与结构相关联,而不管类型T 。 Something that I can call like this:
我可以这样称呼的东西:
A::my_method()
Instead of:代替:
A::<T>::my_method()
I tried implementing a trait called Get on A<T> and call it as follows:我尝试在A<T>上实现一个名为Get的特性,并按如下方式调用它:
struct A<T> {
val: i32,
t: T
}
trait Get {
type ValType;
fn get_val() -> Self::ValType;
}
impl<T> Get for A<T> {
type ValType = i32;
fn get_val() -> Self::ValType {
2
}
}
fn main() {
let a = A {
val: 2,
t: 3.0
};
// This is the call I want, if possible
println!("{:?}", A::get_val());
}
The issue is that it doesn't compile, which is to be expected.问题是它无法编译,这是可以预料的。 The outcome I want is something like this:
我想要的结果是这样的:
impl<T> Get for A<any T> {
type ValType = i32;
fn get_val() -> Self::ValType {
2
}
}
I found on some posts that a workaround is to have a dummy type parameter and call my function as this:我在一些帖子中发现解决方法是使用虚拟类型参数并将我的 function 称为:
struct DummyType;
fn main() {
let a = A {
val: 2,
t: 3.0
};
// This is the call I want, if possible
println!("{:?}", A::<DummyType>::get_val());
}
What you are probably missing is a method receiver.您可能缺少的是方法接收器。
pub struct A<T> {
pub field: usize,
pub something: T,
}
pub trait Getter {
type Output;
fn get(&self) -> Self::Output;
}
impl<T> Getter for A<T> {
type Output = usize;
fn get(&self) -> Self::Output {
self.field
}
}
fn main() {
let a = A { field: 10, something: 3.0 };
assert_eq!(a.get(), 10);
}
Here you can return the state of A
and not just constant.在这里您可以返回
A
的 state 而不仅仅是常量。
First, your design looks wrong.首先,你的设计看起来不对。 If the type is generic, what does it mean to have a non-generic method?
如果类型是通用的,那么拥有非通用方法意味着什么?
Anyway, you can use a sentinel type (and you don't need a trait for that, I don't really get why you put it in the first place):无论如何,你可以使用一个哨兵类型(你不需要一个特征,我真的不明白你为什么把它放在第一位):
impl A<()> {
fn get_val() -> i32 {
2
}
}
The compiler infers T
to be ()
automatically when you call A::get_val()
.当您调用
A::get_val()
时,编译器会自动将T
推断为()
)。
Playground . 游乐场。
Fine, I tried this and rust seems to be okay with it:好吧,我试过了,rust 似乎没问题:
pub trait Get {
type Output;
fn get() -> Self::Output;
}
pub struct A<T>(T);
impl Get for A<()> {
type Output = usize;
fn get() -> Self::Output {
2
}
}
fn main() {
println!("{}", A::get());
}
The ()
is the best pick here as you want to express that parameter is not important to us here but also not declare a type just for that. ()
是这里的最佳选择,因为您想表达该参数在这里对我们并不重要,但也不要为此声明类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.