0

I'm trying to better understand reasoning behind the value types.

Does value/reference types in Nim works same way as in Swift?

Alex Craft
  • 13,598
  • 11
  • 69
  • 133
  • That's a very vague question. What do you mean by "reasoning behind the value types", how do value and reference types work in Swift, and which reference types are you referring to? – lqdev Jan 05 '21 at 12:55
  • @lqdev - I don't know much about it. I saw lots of talks about how Value Types works in Swift on Youtube, and wanted to know if the same is true for Nim so I can watch those and apply that knowledge to Nim. – Alex Craft Jan 06 '21 at 08:32

1 Answers1

2

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:

  1. Value semantics means that the copy owns its memory and lives separately from the copied.

  2. 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:

pietroppeter
  • 1,433
  • 13
  • 30