I need some objects where the properties can be changed in multiple procedures. So I chose the implementation with ref:
type
MyObj = ref object
prop: string
proc doitWithObj(myObj: MyObj) =
myObj.prop = "hallo"
var x: MyObj
x = MyObj()
x.prop = "bon jour"
echo x.prop
doitWithObj((x)
echo x.prop
This works, but is it the best way to do this? Is there a way to define the object as mutable without ref?
Thanks for pointers! (I have forgotten sooo much...)
You can make the parameter in the function be bar
type
MyObj = object
prop: string
proc doitWithObj(myObj: var MyObj) =
myObj.prop = "hallo"
var x: MyObj
x = MyObj()
x.prop = "bon jour"
echo x.prop
doitWithObj((x)
echo x.prop
# but it means it only works with var variables
let y = MyObj()
doitWithObj(y) # compile error
Thanks @amadan and @Stefan_Salewski! Interesting!
In the Nim community what is more commonly used when you want to create a class-like "thing", i.e. a data structure with a fix number of fields and a couple of methods operating on this structure? Objects handed into the methods as var`s or `ref objects handled in directly?
or ref objects
Use ref objects only when you really need them, see e.g. my post in https://forum.nim-lang.org/t/9663. I think that is the advice of most people, but I know in the past, we had a few people, at least one I think, which said they would always use ref objects. But that was 4 or five years ago. Using always ref objects makes the use of Nim more similar to languages where no value objects are available, and all is or behaves like a ref, like in Ruby language. And read a book, the one of Mr. Rumpf, or at least my one. My one is still freely available, and you can create an issue to tell me which information is still missing, so I may get some motivation to fix it.
Very helpful detail, @Stefan_Salewski.
I have read the main chapters of Nim in Action which was good, but I have forgotten quite a bit and it is always good to find out what is "nimonic"...
So thanks again!