Types 如何避免无约束类型参数错误
如果不使用无约束类型,我想不出获得下面功能的方法Types 如何避免无约束类型参数错误,types,rust,Types,Rust,如果不使用无约束类型,我想不出获得下面功能的方法 struct Things<T> { thing: T } trait ThingActions<D> {//will be implemented for 'D's of different types fn foo(&self, data: D) {} fn bar(&self, data: D) {} } impl<T: ThingActions<D>, D&
struct Things<T> {
thing: T
}
trait ThingActions<D> {//will be implemented for 'D's of different types
fn foo(&self, data: D) {}
fn bar(&self, data: D) {}
}
impl<T: ThingActions<D>, D> Things<T> {
fn do_foos(&self, data: D) {//any D with corresponding foo can be used here
self.thing.foo(data)
}
}
impl<T: ThingActions<D>, D: Send + Sync> Things<T> {
fn do_bars_multithreaded(&self, data: D) {
self.thing.bar(&self.thing, data)//this happens in a different thread
}
}
struct Things{
事物:T
}
trait ThingActions{//将为不同类型的'D'实现
fn foo(&self,数据:D){}
fn条(&self,数据:D){
}
暗示事物{
fn do_foos(&self,data:D){//这里可以使用具有相应foo的任何D
self.thing.foo(数据)
}
}
暗示事物{
fn do_bars_多线程(&self,数据:D){
self.thing.bar(&self.thing,data)//这在另一个线程中发生
}
}
我的最终目标是让下面的代码在对foo和bar进行相对较少更改的情况下适用于任何配置
fn main(){
let number = Things {thing: 5isize};
number.do_foos(2);
number.do_foos('a');
}
impl ThingActions<isize> for isize {
fn foo(&self, data: isize){
println!("{}", data + self)
}
}
impl ThingActions<char> for isize {
fn foo(&self, data: char){
println!("{}, {}", data, self)
}
}
fn main(){
设number=Things{thing:5isize};
数字。多福(2);
编号:do_foos('a');
}
isize的impl ThingActions{
fn foo(和self,数据:isize){
println!(“{}”,数据+自身)
}
}
isize的impl ThingActions{
fn foo(&self,数据:char){
println!(“{},{}”,数据,自我)
}
}
在某些情况下,除了“Things”(事物)之外,不使用任何内容。您可以尝试仅在
fn
上绑定D
,而不是在整个结构上:
struct Things<T> {
thing: T
}
trait ThingActions<D> {//will be implemented for 'D's of different types
fn foo(&self, data: D) {}
fn bar(&self, data: D) {}
}
impl<T> Things<T> {
fn do_foos<D>(&self, data: D)
where T: ThingActions<D>
{//any D with corresponding foo can be used here
self.thing.foo(data)
}
}
impl<T> Things<T> {
fn do_bars_multithreaded<D>(&self, data: D)
where T: ThingActions<D>, D: Send + Sync
{
self.thing.bar(data)//this happens in a different thread
}
}
fn main(){
let number = Things {thing: 5isize};
number.do_foos(2);
number.do_foos('a');
}
impl ThingActions<isize> for isize {
fn foo(&self, data: isize){
println!("{}", data + self)
}
}
impl ThingActions<char> for isize {
fn foo(&self, data: char){
println!("{}, {}", data, self)
}
}
struct Things{
事物:T
}
trait ThingActions{//将为不同类型的'D'实现
fn foo(&self,数据:D){}
fn条(&self,数据:D){
}
暗示事物{
fn do_foos(&self,数据:D)
其中T:ThingActions
{//这里可以使用任何具有相应foo的D
self.thing.foo(数据)
}
}
暗示事物{
fn do_bars_多线程(&self,数据:D)
其中T:ThingActions,D:Send+Sync
{
self.thing.bar(data)//这在另一个线程中发生
}
}
fn main(){
设number=Things{thing:5isize};
数字。多福(2);
编号:do_foos('a');
}
isize的impl ThingActions{
fn foo(和self,数据:isize){
println!(“{}”,数据+自身)
}
}
isize的impl ThingActions{
fn foo(&self,数据:char){
println!(“{},{}”,数据,自我)
}
}