gpt4 book ai didi

vector - 如何将可变的Vec 变量传递给函数并获取被索引的项目

转载 作者:行者123 更新时间:2023-12-03 11:36:41 25 4
gpt4 key购买 nike

当我尝试下面的Vec<Ev>代码时,出现[E0308]: mismatched type错误。

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))

}
在此示例中,如何获取Vec索引项目?

最佳答案

函数参数中的语法有点差。可变参数可能会有些困惑,因为有两种不同的表示形式。请参阅this question for a more detailed explanation.
这是更正的elemali_getit函数:

fn elemani_getir(mut dizi: &Vec<Ev>, sira: usize) -> &Ev {
&dizi[sira]
}
您可以这样称呼它:
println!("eleman: {:?}", elemani_getir(&dizi, 3))
请注意, elemani_getir现在返回对 Ev( &Ev)的引用。相反,返回 Ev会导致错误:
cannot move out of index of `std::vec::Vec<Ev>`
要解决此错误,您可以返回对 Ev的引用(如上所示),或者返回与 Ev完全相同的副本(派生 Clone特性):
#[derive(Debug, Clone)]
struct Ev {
semt: String,
fiyat: i32,
}

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

关于vector - 如何将可变的Vec <Something>变量传递给函数并获取被索引的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64624836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com