Skip to content

How can I have pointer of trait object like rust ? #3169

Locked Answered by liuzhishan
liuzhishan asked this question in Q&A
Discussion options

You must be logged in to vote

Hi, I just found a way to achieve dynamic dispatch in mojo. The main idea is to combine the Variant and trait in Mojo. With just a little runtime overhead, the performance should be very good.

I have put the code on my github: https://github.com/liuzhishan/mojo-dynamic-dispatch.

Implemention

A Variant is a sum type, such as enum in rust, or tagged union in c++ (or std::variant in c++17). It can hold a value that could take on several different, but fixed types.

We can define several struct implementing one same trait, such as Echoable. And define a Variant from all these types, which is constrained by one same trait. Then we implement the trait Echoable for the Variant.

For example:

struct

Replies: 2 comments 7 replies

Comment options

You must be logged in to vote
0 replies
Answer selected by liuzhishan
Comment options

You must be logged in to vote
7 replies
@johnsoez4
Comment options

@johnsoez4
Comment options

@liuzhishan
Comment options

@johnsoez4
Comment options

@liuzhishan
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants