Swift 结构类型递归 [英] Swift struct type recursion
问题描述
为什么结构体在 Swift 中不能有递归值类型?这是语言的临时限制还是如预期的那样?
Why can't structs have recursive value types in Swift? Is this a temporary limit of the language or is it as intended?
我觉得将二叉树节点声明为包含递归类型的结构的能力是最自然的实现.
I feel that the ability to declare a binary tree node as a struct with recursive types in it to be the most natural implementation.
struct TreeNode<E>{
var leftNode:TreeNode<E>
var rightNode:TreeNode<E>
var element:E
}
推荐答案
答案就在您的问题中:结构是值类型.如果将子结构 B
包含到结构 A
中,则意味着 A
类型的一个对象的大小为 sizeof(all_other_fields_of_A) + sizeof(B)
.因此,值类型不能递归:它的大小是无限的.
The answer is in your question: structs are value types. If you include a substruct B
into a struct A
, it means, that one object of type A
will have a size sizeof(all_other_fields_of_A) + sizeof(B)
. So, a value type can not be recursive: it would have infinite size.
这篇关于Swift 结构类型递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!