1

When I try the code below for the Vec<Ev> I get a [E0308]: mismatched type error.

use std::fmt::Error;
#[derive(Debug)]

struct Ev {
    semt: String,
    fiyat : i32,
}

impl Ev {
    fn yeni (alan: &str,fiyat: i32) -> Ev {
        Self {
            semt: alan.to_string(),
            fiyat
        }
    }
}


fn dizi_yap(boyut:usize) -> Result<Vec<Ev>,Error> {
    let mut evler = Vec::<Ev>::with_capacity(boyut);
    evler.push(Ev::yeni("melikgazi", 210));
    evler.push(Ev::yeni("kocasinan", 120));
    evler.push(Ev::yeni("hacılar", 410));
    evler.push(Ev::yeni("bünyan", 90));
    Ok(evler)
}

fn elemani_getir(&mut dizi:Vec<Ev>, sira:usize) -> Ev {
    dizi[sira]
    // dizi.get(sira).expect("hata")
}


fn main() {

    let mut dizi = dizi_yap(1).expect("ulasmadi");

    println!("eleman: {:?}",dizi[3]);
    println!("eleman: {:?}",elemani_getir(dizi, 3))

}

How can I get Vec indexed item in this example?

natrollus
  • 321
  • 1
  • 4
  • 11

1 Answers1

1

The syntax in you function arguments is a little off. Mutable arguments can be a little confusing, as there are two different representations. Refer to this question for a more detailed explanation.

Here is the elemali_getit function corrected:

fn elemani_getir(mut dizi: &Vec<Ev>, sira: usize) -> &Ev {
  &dizi[sira]
}

And you can call it like this:

println!("eleman: {:?}", elemani_getir(&dizi, 3))

Note that elemani_getir now returns a reference to Ev (&Ev). Returning Ev instead results in an error:

cannot move out of index of `std::vec::Vec<Ev>`

To get around this error, you can either return a reference to Ev as shown above, or return an exact duplicated of Ev my deriving the Clone trait:

#[derive(Debug, Clone)]
struct Ev {
  semt: String,
  fiyat: i32,
}

fn elemani_getir(mut dizi: &Vec<Ev>, sira: usize) -> Ev {
  dizi[sira].clone()
}
Ibraheem Ahmed
  • 11,652
  • 2
  • 48
  • 54