Structs with Methods

Started by _PJ_, April 29, 2024, 14:09:30

Previous topic - Next topic

_PJ_

Methods are apparently valid within structs:


I am guessing this is because under the hood, they are essentially just a special case of custom type

Maybe the "New" override in this example is also overriding some critical New() definition used for Struct types?
So am I right in thinking this is not really a good nor encouraged practice -
OR
Is there some fancy potential with this?

__
You may be wondering why don't I just use a Type - well, it's because in my actual use case, it's a very brief scope and I will not need huge numbers of these structs to be retained in memory or lists.

__
I found this thread:
https://archive.blitzcoder.org/forums/bmx-ng/106690.html#bottom

But I honestly did not fully understand so was unsur3 if this kind of usage would leak memory or not?

Struct SDATE
Field Year:Int
Field Month:Int
Field Day:Int

Method New(D:Int=0,M:Int=0,Y:Int=-1)
If Y=-1 Then Y=Int(CurrentDate("%Y"))
Self.Day=D
Self.Month=M
Self.Year=Y
End Method

Method Show:String()
Return Day+"-"+Month+"-"+Year
End Method
End Struct

Local D:SDATE = New SDATE
Print D.Show()


Derron

Having the overloaded New() is the way to go - especially if you create immutable structs (create them once and do not alter their "field values" anymore, and making the fields "readonly").


bye
Ron

_PJ_

Quote from: Derron on April 29, 2024, 14:48:17Having the overloaded New() is the way to go - especially if you create immutable structs (create them once and do not alter their "field values" anymore, and making the fields "readonly").


bye
Ron

That's excellent to hear. In my use case the fields are completely static so that's not an issue!
Thanks, Ron!

_PJ_

Took me a while to figure out just where to put "ReadOnly" in the declaration syntax :D

So in case anyone else needs to know::

Struct MyStruct
 Field ReadOnly MyStaticVar1:Int
 Field ReadOnly MyStaticVar2:Int

 Method New(v1:Int, v2:Int)
  Self.MyStaticVar1 = v1
  Self.MyStaticVar2 = v2
 End Method
End Struct