Rust 方法用法演示

Beginner

This tutorial is from open-source community. Access the source code

简介

在本实验中,将演示 Rust 中方法的用法。

注意:如果实验未指定文件名,你可以使用任何你想要的文件名。例如,你可以使用main.rs,并通过rustc main.rs &&./main进行编译和运行。

方法

方法的注释方式与函数类似:

struct Owner(i32);

impl Owner {
    // 像在独立函数中一样注释生命周期。
    fn add_one<'a>(&'a mut self) { self.0 += 1; }
    fn print<'a>(&'a self) {
        println!("`print`: {}", self.0);
    }
}

fn main() {
    let mut owner = Owner(18);

    owner.add_one();
    owner.print();
}

总结

恭喜你!你已经完成了“方法”实验。你可以在 LabEx 中练习更多实验来提升你的技能。