LinkedList的等价物是什么<;T>;在戈兰
在我的用例中,我想知道下面的Java代码将如何在Go中实现LinkedList的等价物是什么<;T>;在戈兰,list,struct,go,linked-list,List,Struct,Go,Linked List,在我的用例中,我想知道下面的Java代码将如何在Go中实现 class TreeNode { public int data; public TreeNode left; public TreeNode right; public TreeNode(){} } LinkedList<TreeNode> treeList = new LinkedList<TreeNode>(); 错误是 ./question4_4b.go:56: can
class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(){}
}
LinkedList<TreeNode> treeList = new LinkedList<TreeNode>();
错误是
./question4_4b.go:56: cannot use current.PushFront((interface {})(node.Left)) (type *list.Element) as type *list.List in assignment
./question4_4b.go:59: cannot use current.PushFront((interface {})(node.Right)) (type *list.Element) as type *list.List in assignment
编辑2:基于我编辑的JamesHenstridge的评论
current = current.PushFront(node.Left)
到
问题解决了。但现在我得到了接口转换错误
[ panic: interface conversion: interface is *binarytree.Tree, not int
goroutine 1 [running]:
Go不支持泛型类型(请参阅常见问题解答问题) 您必须使用以获取所需的键入值 例如,创建您的
TreeNode
类型:
type TreeNode struct {
Data int
Left *TreeNode
Right *TreeNode
}
要迭代包含TreeNode
值的列表:
l := list.New()
// Populate list
for e := l.Front(); e != nil; e = e.Next() {
if tn, ok := e.Value.(TreeNode); ok {
// do something with tn which is of type TreeNode
fmt.Println(tn)
} else {
// e.Value is not of type TreeNode
}
}
如果您组装列表,并且可以确保它只包含类型为TreeNode
的值,则可以忽略类型断言中的错误检查,结果如下所示:
for e := l.Front(); e != nil; e = e.Next() {
// if e.Value would not be of type TreeNode, run-time panic would occur
tn := e.Value.(TreeNode) // tn is of type TreeNode
fmt.Println(tn)
}
编辑:
您得到的错误是:
cannot use current.PushFront((interface {})(node.Left)) (type *list.Element)
as type *list.List in assignment
第行:
current = current.PushFront(node.Left)
current
变量的类型为list.list
,方法current.PushFront()
返回类型为*list.Element
的值。这是两种不同的类型,您不能将*元素
分配给类型为列表
的变量
编辑2:
您的第二个错误:
panic: interface conversion: interface is *binarytree.Tree, not int
是由线路引起的:
fmt.Print(x.Value.(int), " ")
您试图断言值
x.value
的类型是int
,但它不是x.Value
属于*binarytree.Tree
类型,因此断言显然会失败。您所说的“它不允许任何泛型对象”是什么意思?为什么您不能使用容器/列表
?@Ainar-G-我添加了完整的代码。访问树结构时,我遇到了一个错误。PushFront
返回一个元素,而不是一个列表。@DineshAppavoo:您正在将current的结果赋值给current
,但是current
是一个*列表
,而PushFront
返回一个*元素
。你不需要这份作业。@JamesHenstridge-谢谢。这有帮助。但我还是遇到了界面转换的问题,这很有帮助。但还是有错误。我在上面添加了代码。我在访问树时出错struct@DineshAppavoo那么你得到的错误是什么?@DineshAppavoo编辑了我的答案来解释你为什么会得到这个错误。我根据你的建议编辑了代码。但是我正在解决这个问题。返回对象的打印语句中出现错误。我没有解析为树对象。非常感谢。
panic: interface conversion: interface is *binarytree.Tree, not int
fmt.Print(x.Value.(int), " ")