I have some questions about rust grammar


What does '||' mean

In that context, it's what you use to define closures (sometimes called "lambda" or "arrow" functions).

The full syntax is something like |arg_1: String, arg_2: u32| -> ReturnType { do_something_with(arg_1, arg_2) }, but if you don't take any arguments and the compiler can infer the return type from your code, the syntax reduces to || do_something_with(arg_1, arg_2).

If you are familiar with TypeScript, here are some examples of equivalent code:

// Rust
let no_args = || println!("Hello, World!");
let one_arg = |name: &str| println!("Hello, {name}!");
let explicit_return_type = |age: u32, name: &str| -> String { 
  format!("{name} is {age} years old") 

// TypeScript
const no_args = () => console.log("Hello, World!");
const one_arg = (name: string) => console.log(`Hello, ${name}!`);
const explicit_return_type = (age: number, name: string): string => { 
  return `${name} is ${age} years old`; 

i get it. thanks a lot

Can I suggest https://cheats.rs/ as a good place to start when looking up this sort of thing.

The official docs are excellent, but it can be hard to find things if you don't know the search term that applies to what you're looking at (eg in your case it's not obvious that || represents a closure). A simple text search on the cheat sheet can help here - eg a search for || finds 'closure' as the first hit. You can then look through the docs for more on closures.

thank you. it's good.

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.