我正在尝试这样做:调用modify()将使用环境变量更新r。
我读过闭包,但不知道如何将闭包添加到结构中。
fn main() {
let r = Rect::new();
let width:u32 = 10;
let height:u32 = 10;
r.modify();
}
struct Rect{
width:u32,
height:u32
}
impl Rect{
fn new()->Self{
Self{
width:0,
height:0,
}
}
fn modify(&mut self){
self.width = ...;
self.height = ...;
}
}发布于 2022-11-12 12:33:18
你可以做你想做的事,试试!
fn main() {
let mut r = Rect::new();
let width: u32 = 10;
let height: u32 = 11;
let cls = || (width, height);
r.modify(cls);
dbg! {r};
}
#[derive(Debug)]
struct Rect {
width: u32,
height: u32,
}
impl Rect {
fn new() -> Self {
Self {
width: 0,
height: 0,
}
}
fn modify<T>(&mut self, cls: T)
where
T: Fn() -> (u32, u32)
{
self.width = cls().0;
self.height = cls().1;
}
}https://stackoverflow.com/questions/74407853
复制相似问题