&mut self 可变方法
核心概念
&mut self 方法通过可变引用借用实例,可以读取和修改字段的值。当方法需要改变实例的内部状态时,就需要用 &mut self。调用 &mut self 方法要求实例本身是 mut 声明的,并且在调用期间不能有其他任何引用(不可变或可变)存在。
rust
struct Counter {
count: u32,
}
impl Counter {
fn new() -> Self {
Counter { count: 0 }
}
// &self:只读
fn value(&self) -> u32 {
self.count
}
// &mut self:可以修改字段
fn increment(&mut self) {
self.count += 1;
}
fn decrement(&mut self) {
if self.count > 0 {
self.count -= 1;
}
}
fn reset(&mut self) {
self.count = 0;
}
}
fn main() {
// 必须声明为 mut 才能调用 &mut self 方法
let mut counter = Counter::new();
counter.increment();
counter.increment();
counter.increment();
println!("计数: {}", counter.value()); // 3
counter.decrement();
println!("计数: {}", counter.value()); // 2
counter.reset();
println!("计数: {}", counter.value()); // 0
}&mut self 是 self: &mut Self 的简写
rust
struct Buffer {
data: Vec<u8>,
}
impl Buffer {
fn new() -> Self {
Buffer { data: Vec::new() }
}
// 简写形式(常用)
fn push(&mut self, byte: u8) {
self.data.push(byte);
}
// 完整形式(等价,很少用)
fn push_long(self: &mut Self, byte: u8) {
self.data.push(byte);
}
fn len(&self) -> usize {
self.data.len()
}
}
fn main() {
let mut buf = Buffer::new();
buf.push(0x48);
buf.push_long(0x49);
println!("长度: {}", buf.len());
}链式调用
&mut self 方法返回 &mut Self 时可以链式调用。这是构建器模式的基础。
rust
#[derive(Debug)]
struct QueryBuilder {
table: String,
conditions: Vec<String>,
order_by: Option<String>,
limit: Option<u32>,
}
impl QueryBuilder {
fn new(table: &str) -> Self {
QueryBuilder {
table: table.to_string(),
conditions: Vec::new(),
order_by: None,
limit: None,
}
}
// 返回 &mut Self 支持链式调用
fn where_clause(&mut self, condition: &str) -> &mut Self {
self.conditions.push(condition.to_string());
self
}
fn order(&mut self, field: &str) -> &mut Self {
self.order_by = Some(field.to_string());
self
}
fn limit(&mut self, n: u32) -> &mut Self {
self.limit = Some(n);
self
}
fn build(&self) -> String {
let mut sql = format!("SELECT * FROM {}", self.table);
if !self.conditions.is_empty() {
sql.push_str(" WHERE ");
sql.push_str(&self.conditions.join(" AND "));
}
if let Some(ref order) = self.order_by {
sql.push_str(&format!(" ORDER BY {}", order));
}
if let Some(limit) = self.limit {
sql.push_str(&format!(" LIMIT {}", limit));
}
sql
}
}
fn main() {
let mut qb = QueryBuilder::new("users");
let sql = qb
.where_clause("age > 18")
.where_clause("active = true")
.order("name")
.limit(10)
.build();
println!("SQL: {}", sql);
}借用冲突
&mut self 方法调用期间不能有任何其他对实例的引用存在。
rust
struct List {
items: Vec<String>,
}
impl List {
fn new() -> Self {
List { items: Vec::new() }
}
fn add(&mut self, item: &str) {
self.items.push(item.to_string());
}
fn remove_last(&mut self) -> Option<String> {
self.items.pop()
}
fn items(&self) -> &[String] {
&self.items
}
fn count(&self) -> usize {
self.items.len()
}
fn clear(&mut self) {
self.items.clear();
}
}
fn main() {
let mut list = List::new();
list.add("苹果");
list.add("香蕉");
list.add("橘子");
// 正确:&self 方法之后再调用 &mut self 方法
println!("数量: {}", list.count());
list.remove_last();
println!("移除后数量: {}", list.count());
// 错误示例(如果取消注释会编译错误):
// let items = list.items(); // 不可变借用
// list.add("葡萄"); // 可变借用(冲突!)
// println!("{:?}", items); // 使用不可变借用
// 正确:确保不可变借用在可变借用之前结束
let count = list.count(); // 不可变借用在这行结束(NLL)
list.add("葡萄"); // 合法
println!("之前 {} 个,现在 {} 个", count, list.count());
list.clear();
println!("清空后: {}", list.count());
}&mut self 方法修改复杂字段
rust
use std::collections::HashMap;
struct Inventory {
items: HashMap<String, u32>,
log: Vec<String>,
}
impl Inventory {
fn new() -> Self {
Inventory {
items: HashMap::new(),
log: Vec::new(),
}
}
fn add(&mut self, name: &str, quantity: u32) {
let entry = self.items.entry(name.to_string()).or_insert(0);
*entry += quantity;
self.log.push(format!("入库: {} x{}", name, quantity));
}
fn remove(&mut self, name: &str, quantity: u32) -> bool {
if let Some(current) = self.items.get_mut(name) {
if *current >= quantity {
*current -= quantity;
if *current == 0 {
self.items.remove(name);
}
self.log.push(format!("出库: {} x{}", name, quantity));
return true;
}
}
self.log.push(format!("出库失败: {} x{}", name, quantity));
false
}
fn quantity(&self, name: &str) -> u32 {
*self.items.get(name).unwrap_or(&0)
}
fn total_items(&self) -> u32 {
self.items.values().sum()
}
fn display(&self) {
println!("\n=== 库存 ===");
let mut names: Vec<&String> = self.items.keys().collect();
names.sort();
for name in names {
println!(" {} : {}", name, self.items[name]);
}
println!("总计: {} 件", self.total_items());
println!("操作日志({}):", self.log.len());
for entry in &self.log {
println!(" {}", entry);
}
}
}
fn main() {
let mut inv = Inventory::new();
inv.add("螺丝", 100);
inv.add("螺母", 200);
inv.add("垫片", 50);
inv.add("螺丝", 50); // 追加
inv.remove("螺母", 30);
inv.remove("垫片", 100); // 失败:库存不足
inv.display();
}基本示例
用 &mut self 方法实现一个文本编辑器缓冲区:
rust
#[derive(Debug)]
struct TextBuffer {
lines: Vec<String>,
cursor_line: usize,
modified: bool,
}
impl TextBuffer {
fn new() -> Self {
TextBuffer {
lines: vec![String::new()],
cursor_line: 0,
modified: false,
}
}
fn from_text(text: &str) -> Self {
let lines: Vec<String> = text.lines().map(|l| l.to_string()).collect();
let line_count = lines.len();
TextBuffer {
lines: if lines.is_empty() { vec![String::new()] } else { lines },
cursor_line: if line_count > 0 { line_count - 1 } else { 0 },
modified: false,
}
}
// &self 方法:查询
fn line_count(&self) -> usize {
self.lines.len()
}
fn current_line(&self) -> &str {
&self.lines[self.cursor_line]
}
fn is_modified(&self) -> bool {
self.modified
}
fn get_line(&self, index: usize) -> Option<&str> {
self.lines.get(index).map(|s| s.as_str())
}
fn to_string(&self) -> String {
self.lines.join("\n")
}
// &mut self 方法:修改操作
fn insert_line(&mut self, text: &str) {
self.cursor_line += 1;
self.lines.insert(self.cursor_line, text.to_string());
self.modified = true;
}
fn append_to_current(&mut self, text: &str) {
self.lines[self.cursor_line].push_str(text);
self.modified = true;
}
fn delete_current_line(&mut self) -> Option<String> {
if self.lines.len() <= 1 {
// 至少保留一行
let removed = std::mem::replace(&mut self.lines[0], String::new());
self.modified = true;
return Some(removed);
}
let removed = self.lines.remove(self.cursor_line);
if self.cursor_line >= self.lines.len() {
self.cursor_line = self.lines.len() - 1;
}
self.modified = true;
Some(removed)
}
fn replace_current(&mut self, new_text: &str) {
self.lines[self.cursor_line] = new_text.to_string();
self.modified = true;
}
fn move_up(&mut self) {
if self.cursor_line > 0 {
self.cursor_line -= 1;
}
}
fn move_down(&mut self) {
if self.cursor_line < self.lines.len() - 1 {
self.cursor_line += 1;
}
}
fn move_to(&mut self, line: usize) {
if line < self.lines.len() {
self.cursor_line = line;
}
}
fn mark_saved(&mut self) {
self.modified = false;
}
fn display(&self) {
println!("\n--- 缓冲区 ({} 行, {}) ---",
self.line_count(),
if self.modified { "已修改" } else { "未修改" }
);
for (i, line) in self.lines.iter().enumerate() {
let marker = if i == self.cursor_line { ">" } else { " " };
println!("{} {:3} | {}", marker, i + 1, line);
}
}
}
fn main() {
let mut buf = TextBuffer::from_text("fn main() {\n println!(\"hello\");\n}");
buf.display();
// 移动光标并插入新行
buf.move_to(1);
buf.insert_line(" let x = 42;");
buf.display();
// 修改当前行
buf.move_down();
buf.replace_current(" println!(\"x = {}\", x);");
buf.display();
// 删除一行
buf.move_to(0);
buf.delete_current_line();
buf.display();
println!("\n文本内容:\n{}", buf.to_string());
println!("已修改: {}", buf.is_modified());
buf.mark_saved();
println!("保存后已修改: {}", buf.is_modified());
}常见问题
问题一:不可变实例能调用 &mut self 方法吗?
不能。必须用 let mut 声明实例才能调用 &mut self 方法。
问题二:&mut self 方法执行期间能调用 &self 方法吗?
不能直接在 &mut self 方法中通过 self 调用另一个 &self 方法——因为 &mut self 独占了借用。但可以先将需要的数据复制到局部变量,或者重构代码结构来避免冲突。
问题三:链式调用返回 &mut Self 和返回 Self 有什么区别?
| 返回类型 | 含义 | 实例状态 | 适用场景 |
|---|---|---|---|
&mut Self | 返回自身的可变引用 | 原地修改 | 构建器模式(可变引用链) |
Self | 返回新实例(消耗旧实例) | 旧实例被消耗 | 构建器模式(所有权链) |
问题四:能在循环中调用 &mut self 方法吗?
可以,只要没有其他对实例的活跃借用。循环中的可变借用在每次迭代结束时释放,下次迭代重新借用。
适用场景
- 状态更新:修改计数器、标志位等
- 集合操作:添加、删除、修改元素
- 构建器模式:链式调用设置属性
- 缓冲区操作:写入、清空、重置数据
注意事项
- 调用
&mut self方法需要实例是mut的 &mut self独占借用,调用期间不能有其他引用- 返回
&mut Self可以支持链式调用 - NLL 让大部分借用冲突可以通过调整代码顺序解决
&mut self方法内部可以自由读写所有字段- 优先用
&self,只有确实需要修改时才用&mut self
总结
&mut self 方法通过可变引用借用实例,可以读取和修改所有字段。调用它需要实例声明为 mut,并且在调用期间不能有任何其他引用存在。&mut self 方法用于所有需要改变实例状态的场景:更新字段值、操作集合、设置标志位等。返回 &mut Self 可以支持链式调用,这是构建器模式的基础。在设计 API 时,只有确实需要修改实例时才用 &mut self,不需要修改时应该用 &self。