Re: [闲聊] Rust: 从入门到入门

楼主: yam276 ('_')   2025-04-28 15:40:36
: https://space.bilibili.com/361469957/lists/3902595
: 从入门到入门
1. struct 的 impl function
就是其他语言的 class member function
类似许多语言 作为 member 要有 self 才能被实现
如 fn do(&self, ..)
没有 self 的只能用命名空间使用
如 SomeThing::do_something();
参数种类有 (&self)、(&mut self)、(self)
第一个是不可变引用
第二个是可变引用
第三个是会让 function 取得 struct 所有权
i.e. 可以利用第三个特性做 Building Pattern
struct ConfigBuilder { foo: String }
impl ConfigBuilder {
fn set_foo(mut self, f: String) -> Self {
self.foo = f;
self
}
fn build(self) -> Config {
Config { foo: self.foo }
}
}
呼叫时像这样:
let config = ConfigBuilder
.set_foo("value".into())
.build();
这样一整串方法都是以 self 传递所有权的方式来实作
2. 关联函数
不用上面几种 self 当第一个参数
就只能称为关联函数 (associated function)
不能说是 member function
类似C++的静态函数 (无this指标)
也可以这样写
fn square(size: u32) -> Self {
Self {
width: size,
height: size,
}
}
这样会让Self对照变成struct的Rectangle来输出一个长宽大小为size的自己
大部分的 fn new() 都是这种如 String::new()
3. 调用函数
调用函数其实也是语法糖:
rect1.can_hold(&rect2)
// 等同
Rectangle::can_hold(&rect1, &rect2));
所以调用 member function 不会失去所有权
4. #[derive(Copy, Clone)]
定义了 #[derive(Copy, Clone)] 的情况
输入不再是 self 而是 *self
函数不会尝试获得所有权而是复制一份
参考以下:
#[derive(Copy, Clone)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn max(self, other: Self) -> Self {
let width = self.width.max(other.width);
let height = self.height.max(other.height);
Self { width, height }
}
}
fn main() {
let r1 = Rectangle { width: 10, height: 20 };
let r2 = Rectangle { width: 30, height: 15 };
let r3 = r1.max(r2); // OK:r1 和 r2 都是 Copy,不会 move
println!("r1 = {}x{}", r1.width, r1.height); // 可以继续用 r1
println!("r2 = {}x{}", r2.width, r2.height); // 可以继续用 r2
}
作者: crimsonmoon9 (绯月)   2025-04-28 15:42:00
大师我没正式学过rust觉得好难
楼主: yam276 ('_')   2025-04-28 15:42:00
看我给的up主的影片 他讲的很清楚这串都是看他影片的笔记

Links booklink

Contact Us: admin [ a t ] ucptt.com