PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, December 14, 2022

[FIXED] How to partially initialize an ArrayVec?

 December 14, 2022     initialization, rust, syntax     No comments   

Issue

I need structures with fixed maximum size, so the obvious choice seem to be arrayvec crate. However, I'm stuck when ArrayVec is a member of a structure that later needs to be partially initialised:

use arrayvec::ArrayVec; // 0.4.7

#[derive(Debug)]
struct Test {
    member_one: Option<u32>,
    member_two: ArrayVec<[u16; 5]>,
}

pub fn main() {
    let mut test = Test {
        member_one: Some(45678),
        member_two: [1, 2, 3], // <- What to do here to initialise only 3 elements?
    };

    print!("{:?}", test);
}

I'd like to initialise the first three elements of the ArrayVec as it's perfectly capable of holding any number of elements from zero to 5 (in my example), but I can't figure out how to do it.


Solution

You can collect into an ArrayVec from an iterator:

let mut test = Test {
    member_one: Some(45678),
    member_two: [1, 2, 3].into_iter().collect(),
};


Answered By - Peter Hall
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing