Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
動いたり動かなかったりするコード
#[derive(Debug)]
struct Mafuyu {
max_value: usize,
list_of_values: Vec<usize>,
}
impl Mafuyu {
pub fn new(lov: &Vec<usize>) -> Mafuyu {
let max_v = lov.iter().max().unwrap();
Mafuyu {max_value: *max_v, list_of_values: lov.to_vec()}
}
pub fn copy_new(lov: Vec<usize>) -> Mafuyu {
let max_v = lov.iter().max().unwrap();
Mafuyu{max_value: *max_v, list_of_values: lov}
}
}
#[derive(Debug)]
struct Mafuyu2 {
list_of_values: Vec<usize>,
max_value: usize,
}
impl Mafuyu2 {
pub fn new(lov: &Vec<usize>) -> Mafuyu2 {
let max_v = lov.iter().max().unwrap();
Mafuyu2 {list_of_values: lov.to_vec(), max_value: *max_v}
}
pub fn copy_new(lov: Vec<usize>) -> Mafuyu2 {
let max_v = lov.iter().max().unwrap();
// list_of_valuesにlovを渡した時点でlovが使えなくなってしまうため
// max_vの評価をするときに不正なアクセスになっている
// Mafuyu2{list_of_values: lov, max_value: *max_v}
Mafuyu2{list_of_values: lov.to_vec(), max_value: *max_v}
}
}
fn main() {
// reference new
let v = vec![3, 5, 2, 10, 0];
let mafuyu = Mafuyu::new(&v);
let mafuyu2 = Mafuyu2::new(&v);
println!("v={:?}", &v);
println!("{:?}", mafuyu);
println!("{:?}", mafuyu2);
// copy new
let v = vec![3, 5, 2, 10, 0];
let mafuyu_copy = Mafuyu::copy_new(v);
let mafuyu2 = Mafuyu2::copy_new(vec![3, 5, 2, 10, 0]);
// println!("v={:?}", &v); // mafuyu_copyに渡したので使えない
println!("{:?}", mafuyu);
println!("{:?}", mafuyu2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment