Something along the lines of
var x: ref string
new(x)
x[] = "blue"
var y = @["blue", x[], "blue", x[]]
# @["blue", "blue", "blue", "blue"]
x[] = "red"
# @["blue", "red", "blue", "red"]
In practice I have a seq of strings but I need one string in particular to change all instances of itself in a seq when it is modified. Possible?
One could always use std/decls for doing something similar but more backwards(and only a single value) as the following:
import std/decls
var c = @["Hmm", "Hello", "World", "Hmm"]
assert $c == """@["Hmm", "Hello", "World", "Hmm"]"""
var a {.byaddr.} = c[1]
a = "Hello world"
assert $c == """@["Hmm", "Hello world", "World", "Hmm"]"""
a = "Good bye"
assert $c == """@["Hmm", "Good bye", "World", "Hmm"]"""
Though since you want reference semantics so you should probably just make it a seq[ref string] as such to do it more opaquely(atleast in my view):
proc refStr*(s: string): ref string =
new result
result[] = s
proc `$`*(s: ref string): string =
if s != nil:
result = s[]
var a = refStr"Hello"
let c = @[refStr"Hmm", a, refStr"World", a]
assert $c == "@[Hmm, Hello, World, Hello]"
a[] = "Hellllllo"
assert $c == "@[Hmm, Hellllllo, World, Hellllllo]"
The whole point of type safety is that you can't do something like this.
Why not? Code below would be perfectly type safe in TypeScript :)
let list: (number | string | Whatewer)[] = [1, "two", new Whatewer()]
It is Union / Algebraic Type, and it's Type Safe.
With this reasoning you also may say, that Nim Variant Object is unsafe, because unless you manually inspect it's kind you don't know what it is.
And as far as I know the reason why it's not used in Nim is not Types, but Memory Layout.
And as far as I know the reason why it's not used in Nim is not Types, but Memory Layout.
That is very true and it was actually this I had in my head.
With this reasoning you also may say, that Nim Variant Object is unsafe, because unless you manually inspect its kind you don't know what it is.
Sure, I try and avoid Variant Objects as much as I can though as they are more error-prone.
Well either way, I just had an epiphany and solved the issue lol.
A nice thing to do in such cases is to write how you solved it.