Rust自定义智能指针

mac2022-06-30  18

深了,真深了。

use std::ops::Deref; struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } fn hello(name: &str) { println!("Hello, {}!", name); } fn main() { let x = 5; let y = MyBox::new(x); assert_eq!(5, x); assert_eq!(5, *y); let m = MyBox::new(String::from("Rust")); hello(&m); }

转载于:https://www.cnblogs.com/aguncn/p/11440479.html

相关资源:Rust 程序设计语言(2018)中文
最新回复(0)