微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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))

注意:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。