Nim 中的值/引用类型是否与 Swift 中的工作方式相同?

问题描述

我正在努力更好地理解值类型背后的推理

Nim 中的值/引用类型是否与 Swift 中的工作方式相同?

解决方法

是的,值和引用类型在 Nim 中确实像在 Swift 和其他低级编程语言(如 C#、C++、Rust)中一样工作。我的意思是他们在复制方面遵循这些语义:

  1. 值语义意味着副本拥有它的内存并且与被复制的分开存在。

  2. 引用语义意味着复制和复制引用相同的底层内存位置。

(取自this forum answer)。

例如,我将 this swift blog post 翻译为 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))

注意: