self 获取所有权方法
核心概念
self 方法(不带引用符号)会获取实例的所有权,调用后原来的变量就不能再使用了。这种方法用于需要消耗实例的场景——比如将实例转换为另一种类型、提取内部数据、或者在操作完成后让实例自然销毁。self 方法相当于把整个实例"吃掉"了。
struct Wrapper {
value: String,
}
impl Wrapper {
fn new(value: &str) -> Self {
Wrapper { value: value.to_string() }
}
// self 方法:获取所有权,消耗实例
fn into_inner(self) -> String {
self.value // 返回内部数据,Wrapper 被消耗
}
}
fn main() {
let w = Wrapper::new("hello");
// into_inner 消耗了 w
let s = w.into_inner();
println!("提取的值: {}", s);
// w 已经不存在了
// println!("{}", w.value); // 编译错误:value used after move
}三种 self 形式的对比
| 参数 | 含义 | 调用后实例 | 使用场景 |
|---|---|---|---|
&self | 不可变借用 | 可继续使用 | 读取、查询、计算 |
&mut self | 可变借用 | 可继续使用 | 修改字段、更新状态 |
self | 获取所有权 | 不可再使用 | 转换、消耗、提取数据 |
#[derive(Debug)]
struct Token {
content: String,
token_type: String,
}
impl Token {
fn new(content: &str, token_type: &str) -> Self {
Token {
content: content.to_string(),
token_type: token_type.to_string(),
}
}
// &self:只读访问
fn content(&self) -> &str {
&self.content
}
// &self:查询
fn is_keyword(&self) -> bool {
self.token_type == "keyword"
}
// &mut self:修改
fn set_type(&mut self, new_type: &str) {
self.token_type = new_type.to_string();
}
// self:消耗实例,提取内部数据
fn into_parts(self) -> (String, String) {
(self.content, self.token_type)
}
}
fn main() {
let mut token = Token::new("fn", "keyword");
// &self 调用
println!("内容: {}", token.content());
println!("是关键字: {}", token.is_keyword());
// &mut self 调用
token.set_type("identifier");
println!("修改后: {:?}", token);
// self 调用(消耗 token)
let (content, kind) = token.into_parts();
println!("拆解: content='{}', type='{}'", content, kind);
// token 已不可用
}类型转换方法
self 方法最常见的用途是将一个类型转换为另一个类型。Rust 的惯例是用 into_xxx 命名这类方法。
#[derive(Debug)]
struct RawConfig {
host: String,
port: String,
debug: String,
}
#[derive(Debug)]
struct ValidConfig {
host: String,
port: u16,
debug: bool,
}
impl RawConfig {
fn new(host: &str, port: &str, debug: &str) -> Self {
RawConfig {
host: host.to_string(),
port: port.to_string(),
debug: debug.to_string(),
}
}
// self 方法:将原始配置验证并转换为有效配置
fn into_valid(self) -> Result<ValidConfig, String> {
let port = self.port.parse::<u16>()
.map_err(|_| format!("端口 '{}' 无效", self.port))?;
let debug = match self.debug.as_str() {
"true" | "1" | "yes" => true,
"false" | "0" | "no" => false,
_ => return Err(format!("debug 值 '{}' 无效", self.debug)),
};
Ok(ValidConfig {
host: self.host, // 所有权转移,不需要 clone
port,
debug,
})
}
}
fn main() {
let raw = RawConfig::new("localhost", "8080", "true");
println!("原始: {:?}", raw);
// into_valid 消耗 raw,返回 ValidConfig
match raw.into_valid() {
Ok(config) => println!("有效: {:?}", config),
Err(e) => println!("验证失败: {}", e),
}
// raw 已被消耗
// 无效配置
let bad = RawConfig::new("localhost", "abc", "true");
match bad.into_valid() {
Ok(config) => println!("有效: {:?}", config),
Err(e) => println!("验证失败: {}", e),
}
}构建器的 build 方法
构建器模式中,build 方法通常用 self 来消耗构建器,返回最终产品。
#[derive(Debug)]
struct HttpRequest {
method: String,
url: String,
headers: Vec<(String, String)>,
body: Option<String>,
}
struct RequestBuilder {
method: String,
url: String,
headers: Vec<(String, String)>,
body: Option<String>,
}
impl RequestBuilder {
fn new(method: &str, url: &str) -> Self {
RequestBuilder {
method: method.to_string(),
url: url.to_string(),
headers: Vec::new(),
body: None,
}
}
fn get(url: &str) -> Self {
Self::new("GET", url)
}
fn post(url: &str) -> Self {
Self::new("POST", url)
}
// &mut self 方法:设置属性,返回 &mut Self 支持链式调用
fn header(&mut self, key: &str, value: &str) -> &mut Self {
self.headers.push((key.to_string(), value.to_string()));
self
}
fn body(&mut self, body: &str) -> &mut Self {
self.body = Some(body.to_string());
self
}
// self 方法:消耗构建器,生成最终产品
fn build(self) -> HttpRequest {
HttpRequest {
method: self.method,
url: self.url,
headers: self.headers,
body: self.body,
}
}
}
fn main() {
// 链式构建
let mut builder = RequestBuilder::post("https://api.example.com/users");
let request = builder
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token123")
.body(r#"{"name": "张三"}"#)
.build();
println!("{:#?}", request);
// builder 已被 build 消耗
// builder.header("X-Extra", "value"); // 编译错误
// 简单的 GET 请求
let mut get_builder = RequestBuilder::get("https://api.example.com/users");
let get_req = get_builder
.header("Accept", "application/json")
.build();
println!("\n{:#?}", get_req);
}Copy 类型的 self 方法
对于实现了 Copy trait 的类型,self 方法不会消耗实例——会自动复制一份。
#[derive(Debug, Clone, Copy)]
struct Vector2 {
x: f64,
y: f64,
}
impl Vector2 {
fn new(x: f64, y: f64) -> Self {
Vector2 { x, y }
}
// self 方法:因为 Vector2 是 Copy 的,不会消耗实例
fn length(self) -> f64 {
(self.x * self.x + self.y * self.y).sqrt()
}
fn add(self, other: Vector2) -> Vector2 {
Vector2 {
x: self.x + other.x,
y: self.y + other.y,
}
}
fn scale(self, factor: f64) -> Vector2 {
Vector2 {
x: self.x * factor,
y: self.y * factor,
}
}
fn normalize(self) -> Vector2 {
let len = self.length();
if len == 0.0 {
self
} else {
self.scale(1.0 / len)
}
}
}
fn main() {
let v = Vector2::new(3.0, 4.0);
// Copy 类型:self 方法不消耗原始值
println!("长度: {:.2}", v.length());
println!("v 仍然可用: {:?}", v); // v 没有被消耗
let v2 = v.add(Vector2::new(1.0, 2.0));
println!("v + (1,2) = {:?}", v2);
println!("v 仍然可用: {:?}", v);
let normalized = v.normalize();
println!("归一化: {:?}", normalized);
}基本示例
用 self 方法实现一个一次性的数据处理管道:
#[derive(Debug)]
struct DataPipeline {
data: Vec<f64>,
name: String,
steps: Vec<String>,
}
impl DataPipeline {
fn new(name: &str, data: Vec<f64>) -> Self {
DataPipeline {
data,
name: name.to_string(),
steps: Vec::new(),
}
}
// self 方法链:每步消耗并返回新的 Pipeline
fn filter_positive(mut self) -> Self {
self.data.retain(|&x| x > 0.0);
self.steps.push(String::from("过滤正数"));
self
}
fn sort_ascending(mut self) -> Self {
self.data.sort_by(|a, b| a.partial_cmp(b).unwrap());
self.steps.push(String::from("升序排列"));
self
}
fn scale(mut self, factor: f64) -> Self {
self.data.iter_mut().for_each(|x| *x *= factor);
self.steps.push(format!("缩放 x{}", factor));
self
}
fn round(mut self, decimals: u32) -> Self {
let factor = 10f64.powi(decimals as i32);
self.data.iter_mut().for_each(|x| {
*x = (*x * factor).round() / factor;
});
self.steps.push(format!("四舍五入到{}位", decimals));
self
}
fn top_n(mut self, n: usize) -> Self {
self.data.sort_by(|a, b| b.partial_cmp(a).unwrap());
self.data.truncate(n);
self.steps.push(format!("取前{}个", n));
self
}
// 最终消耗:提取结果
fn collect(self) -> Vec<f64> {
println!("\n管道 '{}' 执行了 {} 步:", self.name, self.steps.len());
for (i, step) in self.steps.iter().enumerate() {
println!(" {}. {}", i + 1, step);
}
println!("结果: {:?}", self.data);
self.data
}
}
fn main() {
let data = vec![-3.0, 7.5, 2.1, -1.0, 9.8, 4.3, 0.0, 6.7, -2.5, 8.1];
println!("原始数据: {:?}", data);
// 所有权链式调用
let result = DataPipeline::new("数据清洗", data)
.filter_positive()
.sort_ascending()
.scale(1.1)
.round(1)
.collect();
println!("最终: {:?}", result);
// 另一条管道
let scores = vec![72.0, 85.5, 91.0, 68.3, 95.0, 78.8, 88.2, 55.0, 92.5, 79.1];
let top3 = DataPipeline::new("成绩排名", scores)
.filter_positive()
.top_n(3)
.collect();
println!("前三名: {:?}", top3);
}常见问题
问题一:什么时候该用 self 而不是 &self?
当方法需要消耗实例时用 self:类型转换(into_xxx)、构建器的 build、提取内部数据(into_inner)、一次性操作等。如果只是读取数据就用 &self。
问题二:self 方法和 drop 有什么关系?
self 方法获取所有权后,如果方法结束时值没有被转移出去(返回或赋值),值会在方法结束时被 drop。这和普通的所有权规则一样。
问题三:into_ 前缀是什么惯例?
Rust 社区惯例:into_xxx 表示消耗 self 并转换为另一种类型,as_xxx 表示借用并廉价转换(如 as_str),to_xxx 表示借用并创建新值(如 to_string)。
| 前缀 | self 形式 | 含义 | 例子 |
|---|---|---|---|
into_ | self | 消耗并转换 | into_inner(), into_vec() |
as_ | &self | 借用并转换引用 | as_str(), as_slice() |
to_ | &self | 借用并创建新值 | to_string(), to_vec() |
问题四:Copy 类型的 self 方法会消耗实例吗?
不会。Copy 类型传递 self 时会自动复制一份,原始值不受影响。
适用场景
- 类型转换:
into_xxx方法 - 构建器模式:
build方法消耗构建器 - 数据提取:
into_inner提取内部数据 - 一次性处理:管道模式中的链式消耗
注意事项
self获取所有权,调用后原变量不可用(Copy 类型除外)- 惯例用
into_前缀命名消耗 self 的转换方法 - 构建器的
build方法通常用self - Copy 类型的
self方法不会消耗原始值 - 优先用
&self或&mut self,只有确实需要消耗实例时才用self self方法链需要每个方法都返回Self
总结
self 方法获取实例的所有权,调用后原始变量不再可用。它用于需要消耗实例的场景:类型转换(into_xxx)、构建器的 build 方法、提取内部数据(into_inner)。Rust 的命名惯例是用 into_ 前缀表示消耗 self 的转换。对于 Copy 类型,self 方法会自动复制而不是消耗原始值。在设计 API 时,应该优先使用 &self 和 &mut self,只有确实需要消耗实例的场景才使用 self。