Is it possible to use as-patterntstyle matching in rust?

I checked here but couldnt find anything about the as patterns similar to @ from Haskell

What I want is, say I have a

struct User {
    id:String,
    name:String,
    lastname:String
}

and want to match id only and also want to pass the entire thing to another function

fn sillyFunc(data :User){
   let User{id,..} @ usr = data;
  //do something with id
  anotherFunc(&usr);
}

In this example it makes very little sense since i have access to the data itself but it makes much more sense at the context of a closure where one would pattern match directly on the argument rather than assigning to a seperate variable

It's also @ in Rust. See https://doc.rust-lang.org/reference/patterns.html#identifier-patterns.

Yes, Rust pattern syntax supports @ patterns, as explained in the book here. Note that the syntax is be the other way round from what is in your original post, with the variable name first, so the identifier comes before the @ and the pattern comes after. Your example can thus be done as shown below.

let usr @ User{id,..} = data;

that doesnt seem to be working in loop context
for follower @ FollowerUserData { pk, .. } in self.followers.iter()
The code above gives an error syaing pattern bindings are not allowed after @ which is the entire idea of @ the error message does nothing but create a confusion

It's odd that it isn't documented anywhere, but that restriction seems to have been introduced because it didn't play well with the old borrow checker. There seems to be some discussion about re-enabling it now (see this issue), but it doesn't seem to have been done yet. The examples in the book and reference skirt around the issue by only using subpatterns that don't introduce bindings.

What @jameseb7 said: this is a current limitation of the language that is being worked on; cc @Centril.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.