-
-
Save ZhangHanDong/33eaa28a501fecb364c61421fb5223d5 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 常量中的扩展 | |
const C: &'static Vec<i32> = &Vec::new(); // Vec 的生命周期被扩展为 'static | |
#[derive(Debug)] | |
struct Point { | |
x: i32, | |
y: i32, | |
} | |
fn temp_point() -> Point { | |
Point { x: 1, y: 2 } | |
} | |
#[derive(Debug)] | |
struct Wrapper<T>(T); | |
fn create_string() -> String { | |
String::from("temporary string") | |
} | |
struct Container { | |
data: String, | |
} | |
impl Container { | |
fn new(s: &str) -> Self { | |
Container { | |
data: s.to_string(), | |
} | |
} | |
} | |
fn main() { | |
// 示例 1: 引用字面量 | |
let x = &mut 0; // 临时值 0 的生命周期被扩展到块级作用域 | |
*x += 1; | |
println!("x = {}", x); // 输出: x = 1 | |
// 示例 2: 引用临时字符串 | |
let y = &String::from("hello"); // 临时的 String 被扩展 | |
println!("y = {}", y); // 正常工作,临时值仍然存活 | |
// 对比:不会扩展的情况 | |
// 这段代码会编译失败 | |
// let z = Some(&String::from("world")); // 错误:临时值在这里就被销毁了 | |
// println!("z = {:?}", z); | |
// 可以在整个程序中使用这些值 | |
println!("Constant vector: {:?}", C); | |
let ref p = Point { x: 10, y: 20 }; // 扩展模式 | |
println!("Point through ref: {:?}", p); | |
// 示例 2: 结构体模式中的 ref | |
let Point { ref x, ref y } = temp_point(); // 扩展模式 | |
println!("Coordinates: ({}, {})", x, y); | |
// 示例 3: 元组中的 ref | |
let ref tuple = (String::from("hello"), 42); // 扩展模式 | |
println!("Tuple: {:?}", tuple); | |
// 示例 4: 切片模式 | |
let array = [1, 2, 3, 4]; | |
let [ref first, ref second, ..] = array; // 扩展模式 | |
println!("First two elements: {}, {}", first, second); | |
// 示例 1: 直接引用 | |
let x = &create_string(); // 扩展 | |
println!("Direct reference: {}", x); | |
// 示例 2: 类型转换 | |
let y = &create_string() as &dyn ToString; // 扩展 | |
println!("Cast reference: {}", y.to_string()); | |
// 示例 3: 元组和复合类型 | |
let z = (&create_string(),); // 扩展 | |
println!("In tuple: {}", z.0); | |
// 不会扩展的情况(注释掉因为会编译失败) | |
// 示例 4: 块表达式 | |
// let w = { | |
// let temp = &create_string(); | |
// temp // 错误:临时值被丢弃 | |
// }; | |
// println!("From block: {}", w); | |
// 不会扩展的情况(注释掉因为会编译失败) | |
// let no_extend = Some(&create_string()); // 错误:临时值被丢弃 | |
// println!("From option: {:?}", no_extend); | |
// 多层扩展示例: 不会扩展 | |
// let complex = &[ // 外层引用扩展 | |
// Wrapper( // 结构体扩展 | |
// &Container::new("test") // 内层引用扩展 | |
// ) | |
// ]; // 错误:临时值被丢弃 | |
// println!("Complex data: {}", complex[0].0.data); | |
// 使用 ref 模式的多层扩展 | |
let ref nested = vec![ | |
Container::new("nested"), | |
]; | |
println!("Nested data: {}", nested[0].data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment