21.8 Ignoring Parts of a Value: _
and ..
Often, you only care about certain parts of a value. Rust provides ways to ignore the rest:
_
: Ignores a single element or field. Can be used multiple times._name
: A variable name starting with_
still binds the value but signals intent to potentially not use it, suppressing the “unused variable” warning...
: Ignores all remaining elements in a tuple, struct, slice, or array pattern. Can appear at most once per pattern.
struct Config { hostname: String, port: u16, retries: u8, } fn check_port(config: &Config) { match config { // Match only standard web ports, ignore other fields with `..` Config { port: 80 | 443, .. } => { println!("Using standard web port: {}", config.port); } // Match specific hostname, ignore port using `_`, ignore retries with `..` Config { hostname: h, port: _, .. } if h == "localhost" => { println!("Connecting to localhost on some port."); } // Ignore the entire struct content _ => { println!("Using non-standard configuration on host: {}", config.hostname); } } } fn main() { let cfg1 = Config { hostname: "example.com".to_string(), port: 80, retries: 3 }; let cfg2 = Config { hostname: "localhost".to_string(), port: 8080, retries: 5 }; let cfg3 = Config { hostname: "internal.net".to_string(), port: 9000, retries: 1 }; check_port(&cfg1); // Output: Using standard web port: 80 check_port(&cfg2); // Output: Connecting to localhost on some port. check_port(&cfg3); // Output: Using non-standard configuration on host: internal.net }
Using ..
is more concise than listing all ignored fields with _
, e.g., Config { port: 80, hostname: _, retries: _ }
.