var x= 3.Mpfr
This works just fine
var xsqr = sqr(x)
echo $sxqr
BUT
let xsqr = sqr(x)
echo $sxqr
gives (mpfr: (), initialized: true)
So, what's the difference between 'var' and 'let' here. (If I say const xsqr= somefunction() in C++, this works just fine) So, 'let' is not a simple constant which is initialized at run time
Many thanks for a hint, Helmut
So please, tell a newbie who hasn't written this proc what's wrong with it. Many thanks Helmut
I have omitted the backward quotes since I don't know how to get it into RST
proc $(m: var Mpfr): string =
var buf: cstring
mpfr_asprintf(buf.addr, fmt"%.{ctx_Print_Prec}Rg", m.mpfr.addr)
result = $buf
c_free(buf)
That var is the problem. It requires mutable access to Mpfr, which a let Mpfr forbids. I guess you added that so that you could get m.mpfr.addr? Just remove the var and switch that to m.mpfr.unsafeAddr.
unsafeAddr isn't as scary as it sounds apparently: https://irclogs.nim-lang.org/01-11-2020.html#15:59:16
This looks like a bug to me. If there is a procedure which expects a mutable argument, but the user tries to call it with an immutable argument, the Nim compiler should flag this as an error.
In a larger project it is very hard to find (user) bugs if the Nim compiler just creates a dummy argument which isn't even initialized with the caller's argument.
This happens because there is a $ proc defined for all objects which the compiler assumed that you wanted to use because the one you defined didn't match the type of the object that you wanted to give it.
To get around this and explicitly try to use the proc in your module you can specify the module name. Something like this
echo mymodule.`$`(myObject)
This won't be necessary if the signature of your proc matches the object