type
A = object
str: string
proc getA (str: string) : A =
return A(str:str) # returns A object, not pointer, how do I return a pointer?
proc setStr (obj: var A, str: string): var A {. inline, discardable .} =
obj.str = str # `.` operator dereferences pointer and assigns the value to str ?
return obj
var a = A(str:"works") # a is a pointer?
a.setStr("works too") # call proc with pointer
"".getA().setStr(str: "does not work") # "".getA() is not same as variable a ?
When you declare an object type in nim, it's more like a struct in C. In nim, when ever you assign a new variable to an existing object, it will copy that object over.
For example:
type
A = object
str: string
var a = A(str:"test a")
var b = a
b.str = "test b"
echo a.str
echo b.str
# output:
# test a
# test b
This means that a strict object does not act like as a pointer as you think it does. Also, your last line of the program doesn't work because when you need the return type for the proc getA() to be "var A" instead of just "A".
To declare "pointers" in nim, the recommended way is to use the "ref" keyword, which declares a garbage collected pointer to an object. You could modify your entire code like so:
type
A = ref object # declares a reference type to an object
str: string
proc getA (str: string) : A =
return A(str:str) # returns pointer to A object, since A is declared as a ref object
# got rid of the vars and return type because we don't need them with a reference object
proc setStr (obj: A, str: string) =
# 'dereferencing' happens automatically. this is the same
# as doing "obj[].str = str" where the "[]" are nim's way of dereferencing
obj.str = str
# the reason you had to return the object is because the proc made a copy of your
# object. Since your object is a reference now, you don't need to return it
# return obj
var a = A(str:"works")
a.setStr("works too")
var c = "".getA()
# notice I replaced the colon (:) with an equals (=).
# This is because the call syntax for an object is different than
# calling a proc.
# object -> Object(a: "value", b: "value")
# proc -> some_proc(a="value", b="value")
c.setStr(str="now works")
echo a.str
echo c.str
# output:
# works too
# now works
# and as proof of my previous comment, we'll declare b, a reference to a
var b = a
b.str = "this is both b and a"
echo a.str
echo b.str
# output:
# this is both b and a
# this is both b and a
Hope that helps a bit :)