modularml / mojo

The Mojo Programming Language
https://docs.modular.com/mojo/manual/
Other
23.37k stars 2.6k forks source link

[BUG] Type Annotation Fails on Implicit Variable Declarations #3415

Open sibarras opened 3 months ago

sibarras commented 3 months ago

Bug description

Recently on Nightly we are allowed to implicitly create a variable, without the var keyword. Still we cannot annotate those variables with a type, or create a uninitialized variable.

Steps to reproduce

struct Foo:
    var i: Int

    fn __init__(inout self, i: Int):
        self.i = i

fn m():
    # No Annotations
    var f3 = Foo(1)  # ok
    f4 = Foo(1)  # ok

    # With Annotations
    var f5: Foo = 1  # ok
    f5: Foo = 1  # fails

    # Uninitialized
    var f: Foo  # ok
    f2: Foo  # fails

System information

- Sonoma 14.5 Mac M1
- mojo 2024.8.2419 (1fdb01e1)
- modular 0.9.2 (b3079bd5)
soraros commented 3 months ago

I think it's working as intended.

Moosems commented 3 months ago

You cannot define a variable without var at all, this is intended

sibarras commented 3 months ago

So, it should be more like a feature request?

gryznar commented 3 months ago

For me, it's a bug. If implicit declarations are allowed, annotating them should be also allowed.

Moosems commented 3 months ago

What happens when you do f2: Foo = 1?

sibarras commented 3 months ago

f2: Foo = 1 is not allowed. But f2 = 1 and var f2: Foo = 1 are ok. The problem is when you want to do implicit initialization, you usually tell the compiler using the type annotation, but you can't annotate a implicit variable declaration. So you can't build a String using a StringLiteral, because str = "hello" will always produce StringLiteral. trying str: String = "hello" will fail. You have two options: str = String("hello") or var str: String = "hello"