mojo
mojo copied to clipboard
[Feature Request] Let `Variant` call methods without unwrapping the element when constrained on a trait
Review Mojo's priorities
- [X] I have read the roadmap and priorities and I believe this request falls within the priorities.
What is your request?
This is what I've had to do to build an entrypoint type for several private subtypes (all have the same interface)
struct Socket[
sock_family: StringLiteral, # TODO: change once we have enums
sock_type: StringLiteral,
sock_protocol: StringLiteral,
sock_platform: StringLiteral,
]:
"""Struct for using Sockets. `[*]` in function docstrings means not
available on all platforms!.
"""
alias _linux_s = _LinuxSocket[sock_family, sock_type, sock_protocol]
alias _unix_s = _UnixSocket[sock_family, sock_type, sock_protocol]
alias _windows_s = _WindowsSocket[sock_family, sock_type, sock_protocol]
# TODO: need to be able to use trait regardless of type
var _impl: Variant[Self._linux_s, Self._unix_s, Self._windows_s]
fn __init__(inout self) raises:
"""Create a new socket object."""
@parameter
if sock_platform == SockPlatform.LINUX:
self._impl = Self._linux_s()
elif sock_platform == SockPlatform.UNIX:
self._impl = Self._unix_s()
elif sock_platform == SockPlatform.WINDOWS:
self._impl = Self._windows_s()
else:
# TODO: remove once we have enums
constrained[False, "Platform not supported."]()
async fn socketpair(self) -> Optional[Bool]:
"""Create a pair of new socket objects `[*]`."""
if self._impl.isa[Self._linux_s]():
return await self._impl.unsafe_get[Self._linux_s]()[].socketpair()
...
What is your motivation for this change?
It would be great if it were possible to somehow constraint the variant type with an explicitly declared trait and since all items in the collection conform to that trait, I should be able to call all methods of that trait on that Variant type regardless of what subtype it has inside.
Any other details?
I think this feature + request #3252 will make building, wrapping, and making generic types much easier and lead to much more powerful abstractions:
struct Variant<Constraint: AnyTrait>[*Ts: CollectionElement & Constraint]:
...