Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add type-safe Ok.cast() and Err.cast() methods #561

Merged
merged 1 commit into from
Jul 13, 2023
Merged

Conversation

chriskrycho
Copy link
Collaborator

When working with Result, users sometimes find it useful to cast the other case of the type. For example, given an Ok<string, number> (note: not a Result<string, number>), casting to Ok<string, string> is a safe no-op cast: we know we are in the Ok case, not the Err case, so the transformation is guaranteed to be legal. This is exactly equivalent to two other potential type representations, in fact:

  • Ok<T> | Err<E>
  • Ok<T, never> | Err<never, E>

Implementing either of those types with the performance guarantees we currently have for True Myth and preserving type safety throughout is unfortunately not straightforward (or necessarily even possible), but .cast() allows us to get the benefits anyway.

When working with `Result`, users sometimes find it useful to cast the
*other* case of the type. For example, given an `Ok<string, number>`
(note: not a `Result<string, number>`), casting to `Ok<string, string>`
is a safe no-op cast: we *know* we are in the `Ok` case, not the `Err`
case, so the transformation is guaranteed to be legal. This is exactly
equivalent to two other potential type representations, in fact:

- `Ok<T> | Err<E>`
- `Ok<T, never> | Err<never, E>`

Implementing either of those types with the performance guarantees we
currently have for True Myth *and* preserving type safety throughout
is unfortunately not straightforward (or necessarily even possible),
but `.cast()` allows us to get the benefits anyway.
@chriskrycho chriskrycho merged commit beb110b into main Jul 13, 2023
12 checks passed
@chriskrycho chriskrycho deleted the little-features branch July 13, 2023 02:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant