( 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();
}
#Better Alternative for Box::leak() in this case
27 messages · Page 1 of 1 (latest)
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.
I just wana convert String => &'static str
But as per I researched it's not posssible
Cause a reference to String will be valid up to the life time of String
Whenever you find yourself wanting to do this, the first question to answer is "why"
The second question is "is there another way to solve the actual problem"
So basically I wana
Convert integer to &'static str so I moved with a solution that says use concat!() but it works only with String
Basically I had made a macro that takes an expression and do iteration and return a vector
But I want that vector to contain something like ["1","2"...]
A &'static str
Yeah, I see the macro. As besta as I can tell, you could just make the vector store Strings instead
macro_rules! cannot do this with &str without leaking. You might be interested in the seq_macro crate, which you can use with stringify!
What's that seq_macro.??
?crate seq_macro
Macro to repeat sequentially indexed copies of a fragment of code.
Version
0.3.5
Downloads
17 010 901
Oh
Is it not possible to convert String to &'static str without macro_rule! simply in main
Cause as per what I read on stack overflow it says it's no safe way of doing this
There is nothing special about main, so no.
There is still the question of why do you need a &'static str
Cause I can't return a reference of String from a block of code
Then just return the String instead
Yeah I did it