Edit:
Updated here: https://github.com/onionhammer/onion-nimrod/blob/master/tests/memory.nim
So I decided I'd post this experiment up; I think it would be a nice-to-have if you want to create a GC-ref'ed pointer to a type that isn't a ref type.
Old syntax:
var i: ref MyType
new(i)
i.id = 5
new syntax:
var i= new MyType(id: 5)
On the contrary old way was 3 lines
Can be written in 2 lines:
var i = new(MyType)
i[]=MyType(id:5) # or just i.id=5, if there's only 1 field
Here's a comparison if the generated C (-d:release)
// var i: ref MyType
// new(i)
// i.value = 5
mytype105374* i;
i = 0;
i = (mytype105374*) newObj((&NTI105376), sizeof(mytype105374));
(*i).Value = 5;
// var i = new(MyType)
// i[] = MyType(value: 5)
N_NIMCALL(mytype105374*, new_106215)(void) {
mytype105374* result;
result = 0;
result = (mytype105374*) newObj((&NTI105376), sizeof(mytype105374));
return result;
}
//...
mytype105355* item2;
mytype105355 LOC1;
item2 = new_106215();
memset((void*)(&LOC1), 0, sizeof(LOC1));
memset((void*)(&LOC1), 0, sizeof(LOC1));
LOC1.Value = 5;
(*item2).Value = LOC1.Value;
asgnRef((void**) (&(*item2).Other), LOC1.Other);
// var i = new MyType(value: 5)
mytype105390* item1;
mytype105390* HEX3Atmp_106083;
HEX3Atmp_106083 = 0;
HEX3Atmp_106083 = (mytype105390*) newObj((&NTI105392), sizeof(mytype105390));
(*HEX3Atmp_106083).Value = 5;
item1 = HEX3Atmp_106083;
// var i = (ref MyType)(value: 5)
mytype103401* item1;
mytype103401* LOC1;
LOC1 = 0;
LOC1 = (mytype103401*) newObj((&NTI103403), sizeof(mytype103401));
(*LOC1).Value = 5;
item1 = LOC1;
// var i = new MyRefType(value: 5)
mytype105374* item;
mytype105374* LOC1;
LOC1 = 0;
LOC1 = (mytype105374*) newObj((&NTI105376), sizeof(mytype105374));
(*LOC1).Value = 5;
item = LOC1;
I'm aware of that Araq, but that's even more typing and it's only idiomatic for Nim, and not at all for other languages. A way to allocate a non-ref type into a ref in one line (without semi-colons :P) is useful
Edit: Updated the previous post w/ generated C
Actually when i first was trying to do this i expected it to be
var o = ref Object()
Thats all due to usage of ref elsewhere. I thought "hey if ref is used in defining a reference type then maybe i can construct reference right away using this?"You can easily allocate a reference in one line: just make sure to fully enclose the type by parentheses. However, I'd still prefer a cleaner syntax without parentheses.
var i = (ref MyType)(id: 5)