Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

Rust 函数如何返回一个不定长的字符串数组呢

刚学习rust,中文站点比较少,突然有点为难,虚心求教。

pub fn arg_array(arg: String) -> 怎么声明这个返回值? {
    println!("入参=>{}", arg);
    let array = ["das", "das"];// 这里的array 是通过解析arg,长度不定
    return array
}

刚看到一个比较粗鄙的做法,求更加优雅点

pub fn arg_array(arg: String) -> Vec<&'static str> {
    println!("入参=>{}", arg);
    let array = ["das", "das","dsad"];
    println!("len =>{}",array.len());
    let mut vec = [];
    for i in 0..array.len(){
        vec.push(array[i])
    }
    return vec;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

文档中已经说明,Rust中的数组是固定长度的,不允许改变长度,因此,你只能使用vector来替代。中文站点你可以参考rust中文文档
这里给你找到了一个优雅的写法:

fn parse_core_args(args: Vec<String>) -> (Vec<String>, Vec<String>) {
   let mut rest = vec![];
   // Filter out args that shouldn't be passed to V8
   let mut args: Vec<String> = args
       .into_iter()
       .filter(|arg| {
           if arg.as_str() == "--help" {
               rest.push(arg.clone());
               return false;
           }
           true
       })
       .collect();
   // Replace args being sent to V8
   for idx in 0..args.len() {
       if args[idx] == "--v8-options" {
           mem::swap(args.get_mut(idx).unwrap(), &mut String::from("--help"));
       }
   }
   (args, rest)
}

源码地址


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...