Hi,
In C, if one wants a variable to be modified by a function, one can pass a pointer to said variable. It is also used to avoid passing a copy of a variable to a function or in an assignment.
Since apparently, all the composite types in Nim are reference types (except for numbers) are passed by reference by default in assignments, when does it make sense to declare a variable as a reference to an object of type [T] (since a variable of type [T] is likely to be a reference anyway).
When does it make sense, when is it advantageous, what are the use cases?
Thanks.
That's actually not what ref does. Marking a type with ref makes it heap-allocated, the word ref itself loosely stands for 'ref-counted'.
What you would call a 'ref' in eg. C#, or a pointer in C, is accomplished by var in Nim. For instance:
proc modify(x: var int) =
x = 10
var x = 2
modify x
echo x # 10
In C, if one wants a variable to be modified by a function, one can pass a pointer to said variable.
In most more modern languages like Pascal, Modula, Oberon and Nim we use var parameter type for that.
And in Nim we use ref types only when necessary, generally we use value types. (Well we have a few users that only use ref types...)
For avoiding copy costs Nim does internally pass value types by hidden pointers to procs when variable is large (larger than about 3 times sizeof(float)). I think I told most of that in my Nim book, but maybe some thing is not clear enough still, maybe I will work on it again in the next weeks. If you have read it carefully let me know what is missing or unclear, you can use the github issue tracker or if you have no github account plain email.
@lqdev
the word ref itself loosely stands for 'ref-counted'.
I think you are the only one saying that, and it is not the first time you said it.
For me a ref in Nim is a reference (a managed pointer), and a "ref object" is a reference to an object.
Marking a type with ref makes it heap-allocated,
That is generally true but i believe seq and ref seq are both heap-allocated; the difference is only in their copy behavior. Maybe that is the only exception...
i believe seq
Nim sequences have copy semantics, and the internal data buffer is heap-allocated. More we do not really have to know about seqs. I recently added some more details in my book, as people sometimes ask for details and confuse details. But of course internal working of seqs may change. See http://ssalewski.de/nimprogramming.html#_some_details And again, let me know is something is unclear or wrong.