I'm trying to better understand reasoning behind the value types.
Does value/reference types in Nim works same way as in Swift?
I'm trying to better understand reasoning behind the value types.
Does value/reference types in Nim works same way as in Swift?
yes, value and reference types do work in Nim as in Swift and other low-level programming languages like C#, C++, Rust. By that I mean that they follow these semantics with respect to copy:
Value semantics means that the copy owns its memory and lives separately from the copied.
Reference semantics means that the copy and the copied refer to the same underlying memory location.
(taken from this forum answer).
As an example, I translate this swift blog post to nim (playground):
# port of https://developer.apple.com/swift/blog/?id=10 to Nim
## Example of Value type
type S = object
data: int # I cannot say the default of data is -1. Nim does not have (yet) custom initialization, see accepted RFC https://github.com/nim-lang/RFCs/issues/252
var a = S()
var b = a
a.data = 42
echo (a, b) # ((data: 42), (data: 0))
## Example of Reference type
type C = ref object
data: int
func `$`(c: C): string = "C(data: " & $(c.data) & ")" # there is no default $ for ref objects as there is for objects
var x = C()
var y = x
x.data = 42
echo (x, y) # (C(data: 42), C(data: 42))
Note that:
===
operator like Swift (see this discussion).