プログラムの実行が継続できないような重大な問題をパニックという
パニックは他の言語の例外処理に似ている
Cargo.tomlファイルのpanic=’abort’で異常終了する
let f = File::open("sample.txt");
let f = match f {
Ok(file) => file,
Err(error) => {
panic!("ファイル開けません: {:?}", error)
}
}
アサートはプログラムの途中で値が妥当であるか調べる
assert_eq!(left, right);
let f = 3.7_f64;
assert_eq!(f.floor(), 3.0);
println!("f={}", f);
### メモリ管理
メモリはランタイムが管理するので考える必要はない
Box: std::boxed::Boxを使うことでヒープにメモリを確保することができる
struct Point {
x: i32,
y: i32,
}
impl Clone for Poin {
fn clone(&self) -> Self {
Point {
x: self.x.clone(),
y: self.y.clone(),
}
}
}
fn main() {
let p1 = Point {x: 12, y:25};
let p2: Box<Point> = Box::new(Point {x: 23, y: 45});
println!("{:?}", type_of(p1.clone()));
println!("{:?}", type_of(p2.clone()));
println!("{}, {}", p1.x, p1.y);
println!("{}, {}", p2.x, p2.y);
}
fn type_of<T>(_: T) -> &'static str {
std::any::type_name::<T>()
}
use std::mem;
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point {x: 12, y: 25};
let a = [1,2,3,4,5,6,7,8,9];
println!("pのサイズ={}", mem::size_of_val(&p));
println!("aのサイズ={}", mem::size_of_val(&a));
}