modularml / mojo

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

[Feature Request]: Static attribute of Struct like Class in Python #611

Open ykutaykuta opened 1 year ago

ykutaykuta commented 1 year ago

Review Mojo's priorities

What is your request?

struct Complex: var real: Float32 var imag: Float32

fn __init__(inout self, real: Float32, imag: Float32):
    self.real = real
    self.imag = imag

fn dump(self) :
    print(String(self.real) + " + " + String(self.imag) + "i")

fn main() raises: var a = Complex(1.2, 2.3) var b = Complex(4.5, 5.6) a.dump() b.dump()

Output: 1.2000000476837158 + 2.2999999523162842i 4.5 + 5.5999999046325684i

Expected output: 4.5 + 5.5999999046325684i 4.5 + 5.5999999046325684i

What is your motivation for this change?

Static method, and static attribute is useful in many case. It's a part of programing

Any other details?

No response

drunkwcodes commented 1 year ago

Current behavior is align with python. You maybe get mistake.

ykutaykuta commented 1 year ago

Current behavior is align with python. You maybe get mistake.

In Python we can do

class Complex: real: float imag: float def __init__(self, real, imag): Complex.real = real Complex.imag = imag def dump(self) : print(str(Complex.real) + " + " + str(Complex.imag) + "i") if __name__ == "__main__": a = Complex(1.2, 2.3) b = Complex(4.5, 5.6) a.dump() b.dump()

How to do the same in Mojo, I just try it but Mojo error: cannot access instance field 'real' without an instance of 'Complex'

lattner commented 1 year ago

We currently support static methods, but not static data yet. This is tied into global variable support.