为什么 NamedTuples 和(不可变)结构是分开的?

Bat*_*aBe 6 struct namedtuple julia

有人可以解释为什么NamedTuples 和 immutable structs 是分开的,而不是像匿名函数一样是匿名NamedTuple的吗?它们在概念上看起来具有相同的结构(我也想知道它们是否具有不同的内存布局),尽管它们有不同的方法来访问它们的字段(下面的示例)。实现s的方法似乎非常合理,但我可能只是不知道不这样做的充分理由。structfunction (x) x^2 endNamedTuplestruct

struct X; a; b; c; end

Xnt = NamedTuple{(:a,:b,:c), Tuple{Any, Any, Any}}

t1 = (10, 20.2, 30im)
#
#
# t1[1]          indexing by position
# t1[1:2]        slicing
# for el in t1   iteration

x1 = X(t1...)
# x1.a           getting field

xnt1 = Xnt(t1)
# xnt1.a         getting field
# xnt1[:a]       indexing by field
# xnt1[1]        indexing by position
#
# for el in t1   iteration
Run Code Online (Sandbox Code Playgroud)

jli*_*ing 10

每个具有相同名称和字段类型的 NamedTuple 实例都具有相同的类型。不同的结构(类型)可以具有相同数量和类型的字段,但类型不同。

  • 本质上,名义子类型与结构子类型。 (3认同)