I will preface this by admitting that it is only a minor inconvenience.
However
The official manual https://nim-lang.org/docs/manual.html#types-object-construction demonstrates creating a pointer variable and assigning a value to it (in var a3 line).
type
Student = object
name: string
age: int
PStudent = ref Student
var a1 = Student(name: "Anton", age: 5)
var a2 = PStudent(name: "Anton", age: 5)
# this also works directly:
var a3 = (ref Student)(name: "Anton", age: 5)
# not all fields need to be mentioned, and they can be mentioned out of order:
var a4 = Student(age: 5)
I tested it in nim 2.0.2 and it works.
I tried to use the same principal with seq[int] as follows
var var1 = (ref seq[int]) @[1,1,1,1]
I get this when i compile.
Error: type mismatch: got 'seq[int]' for '@[1, 1, 1, 1]' but expected 'ref seq[int]'
Is there proper syntax to achieve it?
I know that this works, just checking if the first one can work
var var1 = new seq[int]
var1 = @[1,1,1,1]
var var1 = new seq[int]
var1 = @[1,1,1,1]
will not work, because ref is sort of auto-managed pointer and requires manual dereference (as if it's a pointer). For example,
var1[] = @[1,1,1,1]
# `[]` is the dereferencing operator.
As @jyapayne stated, you don't need to use a ref seq in order to make it be placed on the heap. It already is.
What we refer to as seq is like a pointer to the heap, or an object-like thing that holds such a pointer. A ref seq[T] is like a pointer-to-pointer. Quite pointless. So we normally don't use it, unless when needing reference semantics.
I forget the brackets, my bad.
I understand that sequences are heap-allocated.
I wanted to have several variables point to the same sequence, so this is how I set it up.
var
var1 = new seq[int]
var2 = var1
var1[] = @[1,2,3]
var2[][1] = 2
To be honest, I am still figuring out how this is useful, but wanted to discover the syntax of single line assignment anyway (if it is even possible)var
var1 = @[1,2,3]
var2 = var1.addr
--- the rest of the code---
I understand that this also works. Maybe too much time has been wasted on a minor inconvenience. But it is great that there are many ways to achieve the same thing
Thanks for the help!
Worth noting this gets a ptr seq[int] and not ref seq[int] which means you need to ensure the lifetime manually.
If one is making many ref types one can simply do:
proc new[T: not ref](val: sink T): ref T =
result = new T
result[] = val
var a = new @[10 ,20, 30]