Why are NamedTuples and (immutable) structs separate?

Viewed 312

Can someone explain why NamedTuples and immutable structs are separate instead of NamedTuples being an anonymous struct like there are anonymous functions function (x) x^2 end? They look like they have the same structure conceptually (I would also like to know if they have a different memory layout), though they have different methods to access their fields (example below). It seems very plausible to implement the NamedTuple methods for structs, but I may just not be aware of a good reason not to do that.

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
2 Answers

Every single NamedTuple instance with the same names and field types is of the same type. Different structs (types) can have the same number and type of fields but are different types.

A named tuple has names for each column in the tuple. Named tuples are an alternative to a dataframe. When instantiating the namedTuple, you pass the list of field names as a list. Named tuples create a specification contract for expected fields and reduce the chance of code breaking.

Related