In swift this fails
struct Node {
var val: String
var parent: Node
}
with error error: value type 'Node' cannot have a stored property that recursively contains it
but this works
struct Node {
var val: String
var parent: [Node]
}
What is the reasoning behind this behavior?
Instances of a ref struct type are allocated on the stack and can't escape to the managed heap. To ensure that, the compiler limits the usage of ref struct types as follows: A ref struct can't be the element type of an array. A ref struct can't be a declared type of a field of a class or a non- ref struct.
A ref struct variable can't be used in iterators. Typically, you define a ref struct type when you need a type that also includes data members of ref struct types: In .NET, examples of a ref struct are System.Span<T> and System.ReadOnlySpan<T>.
Typically, you define a ref struct type when you need a type that also includes data members of ref struct types: In .NET, examples of a ref struct are System.Span<T> and System.ReadOnlySpan<T>. You also use the struct keyword in the struct constraint to specify that a type parameter is a non-nullable value type.
Sign in to your account Unity is a game engine that uses C# extensively. We're in need of a way to have a struct that contains one or more pointers to other structs that we want to be able to read/write from/to.
Basically, a struct cannot have a property that is of it's own type because a struct is a value type. That means that every time it's used it's a new copy - by value. The way the compiler works is that it needs to compute a set size in memory for a struct. A class, on the other hand, is more flexible in that sense. An array is a little more complicated - it's a struct wrapper around an object. The compiler can deal with an unknown array size in a struct, but it can't deal with custom object that might have infinite recursive values in it. Each node can have a node with another node, with another node, etc, etc... It would need to set infinite memory for the struct. For more detail see this excellent article: Bidirectional associations using value types in Swift
The reason for this compile error is memory allocation:-
Value types are fixed structures and they occupy a fixed space in memory, in registers and the stack, depending on its size. That space is pre-determined by the type and must be known at compile time.
So, the compiler needs to know how much space to reserve for a given struct value. But, how could that space be calculated if the value could contain another value of the same type, and that value could contain another one, and so on, and so on, and so on…(recursion)?
It is impossible to calculate the space needed, so the compiler simply says N0!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With