MST

星途 面试题库

面试题:Rust中结构体方法与关联函数的区别

请详细阐述Rust结构体方法与关联函数在定义、调用方式、参数传递等方面的区别,并各举一个简单的示例代码。
41.8万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试

定义区别

  • 结构体方法:定义在结构体内部,使用impl块。第一个参数通常是self,表示结构体实例。
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}
  • 关联函数:同样定义在impl块中,但第一个参数不是self。它不依赖于结构体的实例。
struct Point {
    x: i32,
    y: i32,
}

impl Point {
    fn origin() -> Point {
        Point { x: 0, y: 0 }
    }
}

调用方式区别

  • 结构体方法:通过结构体实例来调用。
let rect = Rectangle { width: 10, height: 5 };
let area = rect.area();
  • 关联函数:通过结构体名来调用。
let p = Point::origin();

参数传递区别

  • 结构体方法:第一个参数是结构体实例的引用(如&self&mut selfself),这样可以访问和修改结构体的字段。
impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}
let rect1 = Rectangle { width: 10, height: 5 };
let rect2 = Rectangle { width: 8, height: 3 };
let can_hold = rect1.can_hold(&rect2);
  • 关联函数:参数根据函数定义而定,没有特殊的与结构体实例相关的参数要求。
impl Point {
    fn new(x: i32, y: i32) -> Point {
        Point { x, y }
    }
}
let p = Point::new(3, 4);