Is it possible to cast type `std::result::Result`

2020-05-09 22:32发布

Is it possible to cast type std::result::Result to minhook::Hook using the minhook library?

test =
    unsafe {
        minhook::Hook::<fn(f32, *mut UserCmd) -> bool>::create::<fn(f32, *mut UserCmd) -> bool>(hook_createmove, fn_ptrs.addy)
    } as minhook::Hook<fn(f32, *mut UserCmd) -> bool>;

minhook::Hook:::create returns a std:::result::Result<Hook>

As you can see, this is giving me the non-scalar cast problem. Is there a workaround for this?

标签: rust
1条回答
萌系小妹纸
2楼-- · 2020-05-09 23:35

Result<T, E> is the standard type for representing success or failure of an operation in Rust. It's declared roughly like this:

enum Result<T, E> {
    Ok(T),
    Err(E),
}

Any function that could fail in a fairly recoverable way (examples: attempting to open a file that does not exist or a parsing error occurred when reading a corrupted JSON file) will usually return a Result. See also What's the benefit of using a Result?.

You should not attempt to reinterpret result objects. Casting is not possible, and you should definitely not use transmutation. Instead, you should always (and I do mean always) use proper methods for handling them. Pointing out just a few examples of result handling:

  • To assertively retrieve the positive outcome (the object of type T), use the unwrap() method. The program will panic if the result holds an error. This is often used when you are sure that no errors can happen in that particular case, or when you really want the program to terminate when that happens.

  • In some other cases, you want to propagate an error out of a function. This is most elegantly achieved with the ? operator.

The Rust Programming language provides a comprehensive section on Error Handling, and Rust developers are strongly encouraged to understand these concepts.

查看更多
登录 后发表回答