简体   繁体   中英

How to match on a struct with private fields in Rust?

I have a function which returns an error type that contains private fields. I want the caller to match on this error type, and when matched, print a hardcoded error message. That's because this error type already has a specific meaning, so I'm not interested in the message that err.display() would return.

However, the function could return a different error type in the future. If that happens then I want existing callers to get a compilation error, so that they can update the error message that they print.

However, if callers match on Err(_) , then a change in the error type doesn't result in a compilation error.

How do I solve this? One way would be to match on the specific error type, but that doesn't seem possible if the error type has private fields.

Here's example code:

use std::ffi::{CString, NulError};

fn create_cstring() -> Result<CString, NulError> {
    return CString::new("hello");
}

fn main() {
    match create_cstring() {
        Ok(val) => println!("Output: {:?}", val),
        Err(_) => println!("Error: input contains forbidden null bytes"),
    };
}

Suppose I change create_cstring() 's signature and make it return something other than NulError. How do I make the match block fail to compile?

Use .. to match the private fields:

use std::ffi::{CString, NulError};

fn create_cstring() -> Result<CString, NulError> {
    return CString::new("hello");
}

fn main() {
    match create_cstring() {
        Ok(val) => println!("Output: {:?}", val),
        Err(NulError{..}) => println!("Error: input contains forbidden null bytes"),
    };
}

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM