#Better Alternative for Box::leak() in this case

27 messages · Page 1 of 1 (latest)

mortal belfry
#
    ( for $arg1:ident in $arg4:expr  ) => {
        {
            let mut vec = Vec::new();
            for $arg1 in $arg4{
                vec.push($arg1);
            }
            vec
        }
    };
    ( for $arg1:ident in $arg4:expr => String ) => {
        {
            let mut vec = Vec::<String>::new();
            for $arg1 in $arg4{
                vec.push($arg1.to_string());
            }
            vec
        }
    };

      ( for $arg1:ident in $arg4:expr => &str ) => {
        {
            let mut vec = Vec::<&str>::new();
            for $arg1 in $arg4{
                let string_value = Box::leak(Box::new($arg1.to_string()));  
                vec.push(string_value.as_str());
            }
            vec
        }
    };
}
fn main() {
    let a = expr!(for i in (0 ..= 10).rev() => String);
    let a = expr!(for i in (0 ..= 10).rev() => &str);
    println!("{:?} ",a);
    let a = "".to_string().to_owned().as_str();
}
prime grail
#

Yes, there are better ways? But I am not sure what you are trying to accomplish.

#

This would cause memory leaks whenever the macro is encountered.

#

If the goal is to create a Vec of strings or string slices you can also just use the collect method.

mortal belfry
#

But as per I researched it's not posssible

#

Cause a reference to String will be valid up to the life time of String

random fox
#

The second question is "is there another way to solve the actual problem"

mortal belfry
#

Convert integer to &'static str so I moved with a solution that says use concat!() but it works only with String

mortal belfry
#

But I want that vector to contain something like ["1","2"...]

#

A &'static str

random fox
random fox
mortal belfry
#

What's that seq_macro.??

random fox
#

?crate seq_macro

cunning tapirBOT
#

Macro to repeat sequentially indexed copies of a fragment of code.

Version

0.3.5

Downloads

17 010 901

mortal belfry
#

Oh

mortal belfry
#

Cause as per what I read on stack overflow it says it's no safe way of doing this

random fox
kind orbit
#

There is still the question of why do you need a &'static str

mortal belfry
random fox
mortal belfry