< 返回版块

xinlingjushi 发表于 2021-02-08 14:42

Tags:rust,struct,fn

struct Ent{ num:i32 , name:String, gl:i32, sl:i32 }

impl Ent { fn new(num: i32 ,name: &str ,gl: i32) -> Ent { Ent { num: num , gl:gl, name: name.to_string(), sl:0 } } fn println(&self) { println!("{},{},{},{}",self.num,self.gl,self.name,self.sl); }

fn clear(&mut self)  {
     self.num =0;
     self.gl =0;
     self.name ="";
     self.sl=0;
}

fn add(&mut self, other: &mut Ent)  {
        ??
}

fn edit(&mut self, other: &mut Ent)  {
        ??
}

fn compare(&self, other: &Ent) -> bool {
    self.gl > other.gl && self.sl > other.sl
}

}

评论区

写评论
作者 xinlingjushi 2021-02-09 15:05

多谢, 我是想针对struct的属性做变化,之前对可变性的了解还是有点微薄。 这是我自己的实现,也算是结贴了 https://blog.csdn.net/qq_39308071/article/details/113767779

Neutron3529 2021-02-09 11:49

盲猜你想要的可能是这个:

struct Test();
impl Test{
    fn new()->Self{Self()}
}
trait FnWeWantToAdd{
    fn fn_we_want_to_add(&self){}
}
impl FnWeWantToAdd for Test{
    fn fn_we_want_to_add(&self){println!("Ok.")}
}
fn main(){
    Test::new().fn_we_want_to_add()
}
Cupnfish 2021-02-08 16:37

没看懂具体在问什么,是想问如何给结构体重载操作符么?比如给这个结构体实现+这个操作?

1 共 3 条评论, 1 页