Why never matching? the vector have the info but the matching never occurs.
thanks
The vector will only match that pattern if the vector has length one. It seems like your vector has multiple elements.
Solution:
// Rough translation of the iteration without a `for` iterator.
let mut it = values.into_iter();
loop {
match it.next() {
Some(x) => println!("{}", x),
None => break,
}
}
https://brson.github.io/rust-anthology/1/effectively-using-iterators.html
Perhaps you meant the pattern [_, "APP_ENV=local"]
, but more likely you want <[T]>::contains()
:
if sort_data.contains(&"APP_ENV=local") {
println!("Send RCE");
// ...
}
Thanks bro but i don't want to use IF of every case i think match are more idiomatic!
If you want to check the second value in the array against a series of values, then indeed, match
is more idiomatic. Like:
match sort_data[1] {
"..." => { /* ... */ }
// ...
}
However, if you want to test for some values if contained in the array, separately, then match
is not meant for that, even if the syntax is nice. A series of if
s is the right thing to do. (there are some other clever possibilities with iterators, however).
If you may or may not have multiple elements, why not use the ..
operator with your match?
match sort_data[..] {
["APP_ENV=local", ..] => todo!(),
_ => todo!(),
}
You can also bind the rest of the slice to a variable with @
(e.g. ["APP_ENV=local", rest @ ..]
).
it doesn't work bro the code for work is
let mut it = values.into_iter();
loop {
match it.next() {
Some(x) => println!("{}", x),
None => break,
}
}
if the match don't have a value defined into the match never enter in the Vector, in others words: Match can't work whit ranges.
Can you say more than "it doesn't work". If you show us the compile error then we can help you debug it.
It works just fine for me:
fn main() {
let a = vec!["first", "second", "third"];
let b = vec!["fourth", "fifth", "sixth"];
let c = vec!["seventh"];
print(a);
print(b);
print(c);
}
fn print(item: Vec<&str>) {
match item[..] {
["first", ..] => println!("Starts with first"),
["fourth", ..] => println!("Starts with fourth"),
_ => println!("Starts with something else"),
}
}
I just checked your screenshot in more detail... Your problem is that sort_data
is a vec!["APP_NAME=SmartJack", "APP_ENV=local"]
. The APP_ENV=local
is the second element, yet all the proposed solutions have expected APP_ENV=local
to be the first.
Your loop
works because it'll fail the check on the first pass then find APP_ENV=local
on the second time through.
To match on the second item you could do something like this:
match sort_data[..] {
[_, "APP_ENV=local", ..] => println!("Found the local env"),
_ => println!("Ssomething else"),
}
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.