modularml / mojo

The Mojo Programming Language
https://docs.modular.com/mojo
Other
22.37k stars 2.55k forks source link

[BUG] using walrus operator needs variable declaration #2841

Open artemiogr97 opened 1 month ago

artemiogr97 commented 1 month ago

Bug description

For now it is needed to declare a variable before being usable with the walrus operator

Steps to reproduce

The following code works:

var i = 1
var j: Int
if j:=i+1:
    print(j)

It should be possible to do:

var i = 1
if j:=i+1:  # for now this causes an error here: use of unknown declaration 'j'
    print(j)

See comment here: https://github.com/modularml/mojo/pull/2742#discussion_r1615198526

System information

- wsl ubuntu 22.04 using windows 11
- mojo 2024.5.2605 (9c328b12)
- modular 0.7.2 (d0adc668)
nmsmith commented 1 month ago

This isn't necessarily a bug. It's unclear how the walrus operator should work in Mojo. If the variable didn't previously exist, maybe the following syntax should be required: if var j := i+1:.

artemiogr97 commented 1 month ago

Just talking about variable declaration (not initialization), I guess guess it makes sense to have the same behavior as something like "for i in range(10):" where it is not needed to declare the "i" variable. I'm not against using var with the operator.

Personally I was just asked to create an issue for this by a maintainer.