0

I have this code :

trait State:

    fn to_string(self) -> String:
        ...

struct StateTtt(State):

    fn __init__(inout self):
        pass

    fn to_string(self) -> String:
        return "ABC"

fn get_state() -> State:
    return StateTtt()

fn main():
    var s = get_state()
    print(s.to_string())

But it gives me the error :

cannot implicitly convert 'StateTtt' value to 'State' in return value

But the StateTtt struct implements the State trait, so why it cannot be converted ?

Of course, this is a simplified version of my code. In the real code, the getState function will create a struct instance based on a parameter.

1 Answer 1

0

First, welcome to Mojo🔥!

A trait (State) is not a returnable type, but rather a description of how a type can conform to an expected implementation of expected features. You can read more about traits here: https://docs.modular.com/mojo/manual/traits

And here is an example of your code with some modifications:

trait State:
    fn to_string(self) -> String:
        ...

@value
struct StateTtt(State, Stringable):
    var some_state_data: Int

    fn __init__(inout self, some_state_data: Int = 0):
        self.some_state_data = some_state_data

    fn __str__(self) -> String:
        return "StateTtt(" + str(self.some_state_data) + ")"
    
    fn to_string(self) -> String:
        return str(self)

fn get_state() -> StateTtt:
    return StateTtt()

fn main():
    var s = get_state()
    print(s)

Result:

StateTtt(0)

Please note that get_state() is no different than StateTtt(). Since I'm not clear on your objective, I'm just answering the question as I see it and not making architectural tweaks.

Also note that __str__ is the Mojo standard for the already-existing Stringable trait, which allows a struct to be str()'d into a String.

Since your code sample does not lay out full concept behind State and StateTtt, I am unsure if this answer is fully answering the "question behind the question," so to say. But I hope I'm getting you moving in the right direction!

Of note: this answer is current as of Mojo nightly, version 2024.5.1515 (077049dc). The language is still evolving; subtle changes could occur between this post and any future reader.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.