1

So for easy initialization of a vector there is there vec! macro.

let mut vec_of_zeroes: Vec<usize> = vec![0;10];

I was wondering if there was an easy standard macro for initializing a linked list too?

use std::collections::LinkedList;

let mut list_of_zeroes: LinkedList<usize> = /*macro here?*/;

If not, no worries. Thanks for you time.

yosmo78
  • 489
  • 4
  • 13

2 Answers2

4

No, there is no such macro in the standard library. Indeed, there is no analogous macro for any other data structure, even HashMap / BTreeMap, which are much more frequently used.

However, the crate velcro provides a linked_list! macro that does what you want (and has some other neat features).

Note that std::collections::LinkedList lacks some features that make linked lists attractive - there is no cursor-based API, for instance. In most cases you should probably use Vec or VecDeque instead.

trent
  • 25,033
  • 7
  • 51
  • 90
3

There is no linked list macro, but you could use the .extend() method to achieve something similar:

use std::collections::LinkedList;

fn main() {
    let mut a: LinkedList<u32> = LinkedList::new();
    
    a.extend(&[0; 10]);
    
    println!("{:?}", a);
}

Playground

If you want to have a single line initialization, you could use some other iterator methods as suggested by @Stargateur in the comments. This method also allows the variable to be immutable, if you wanted that for some reason.

use std::collections::LinkedList;

fn main() {
    let a: LinkedList<u32> = [0; 10].iter().copied().collect();
    
    println!("{:?}", a);
}

Playground

Herohtar
  • 5,347
  • 4
  • 31
  • 41