gpt4 book ai didi

types - 如何避免无约束类型参数错误

转载 作者:行者123 更新时间:2023-12-03 11:45:31 26 4
gpt4 key购买 nike

如果不使用不受约束的类型,我想不出一种方法来获得以下功能。

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
}
}

我的最终目标是让下面的代码适用于 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)
}
}

也有可能的情况是除了“事物”之外什么都不使用。

最佳答案

你可以尝试绑定(bind)D仅在 fn 上,而不是整个结构:

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)
}
}

关于types - 如何避免无约束类型参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61970607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com