-4

for example ,

enum People {
    Bad,
    Good,
}

I would like to initialize a variable with enum type,
I would then have if statement that assign enum value to variable,
And I would like to use variable like:

fn main(){
    People he;
    if sth {
         he = People::Good;
    }else{
         he = People::Bad;
    }
    dosth(&he);
}

I looked at the docs but cant figure out how to.

4
  • Your syntax is not valid Rust. Commented Jan 10, 2023 at 16:53
  • I am inclined to say that these two questions answer this one: stackoverflow.com/questions/32180684/… stackoverflow.com/questions/73432621/… Commented Jan 10, 2023 at 16:59
  • @E_net4thecommentflagger I saw the second, but don't think this is a duplicate of either. The real question is what we should do with users that clearly didn't even try to learn the language. I'd like to close this question, but I can't find a valid reason. Commented Jan 10, 2023 at 17:02
  • Remember, in Rust if can return a value, so he = if ... is valid code. Commented Jan 10, 2023 at 17:02

1 Answer 1

3

You are probably trying to write:

enum People {
    Bad,
    Good,
}

fn dosth(p: &People) {}

fn main() {
    let he;
    if true {
        he = People::Good;
    } else {
        he = People::Bad;
    }
    dosth(&he);
}

Rust uses the keyword let to define a variable. You can assign it a type, like let he: People;, but usually Rust is able to figure out the type by itself. Rust is very strongly typed, if it can't figure out the type, it will give you a compiler error.

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.