1.定义方式不同
方法定义:
// self或&self
fn 方法名(&self, 参数)->返回值{
// 方法体
}
关联函数定义:
fn 函数名(参数) 返回值{
// 函数体
}
// 例
fn new(x:i32, y:i32) -> Rectangle{
Rectangle {
x: x,
y: y,
}
}
2.调用方式不同
方法调用,使用“.” ,例:
rect1.area()
关联函数调用,使用“::”,类似其他语言的静态方法,例:
let a = Rectangle::new(12, 24);
示例代码
struct Rectangle{
width:u32,
height:u32,
}
impl Rectangle{
// new 关联函数
fn new(x:i32, y:i32) -> Rectangle{
Rectangle {
x: x,
y: y,
}
}
//这个结构体拥有求面积的方法
fn area(&self)->u32{
return self.width * self.height;
}
}
fn main() {
let rect1 = Rectangle::new(12, 24);
println!("the rectangle's area is {}",rect1.area());
}