Creating a vector of zeros for a specific size

后端 未结 4 1665
挽巷
挽巷 2020-12-01 15:20

I\'d like to initialize a vector of zeros with a specific size that is determined at runtime.

In C, it would be like:



        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 16:20

    Here is another way, much shorter. It works with Rust 1.0:

    fn zeros(size: u32) -> Vec {
        vec![0; size as usize]
    }
    
    fn main() {
        let vec = zeros(10);
        for i in vec.iter() {
            println!("{}", i)
        }
    }
    

提交回复
热议问题