Go 访问结构内声明的列表时发生类型断言错误
我创建了一个具有列表的结构,其中包含对相同结构类型的值的引用。我不熟悉go语言,无法找到一种方法来访问自动解析为上述结构类型的值。在java中类似于此:Go 访问结构内声明的列表时发生类型断言错误,go,Go,我创建了一个具有列表的结构,其中包含对相同结构类型的值的引用。我不熟悉go语言,无法找到一种方法来访问自动解析为上述结构类型的值。在java中类似于此: class Node{ String value ; String key; List<Node> children = new ArrayList<Node>(); public Node(String key, value) { // rest of the code
class Node{
String value ;
String key;
List<Node> children = new ArrayList<Node>();
public Node(String key, value) {
// rest of the code follows
}
}
class AccessNode {
public static void main(String args[]) {
Node node = new Node("key", "value");
// The values automatically resolve to type Node.
for(Node node : node.children) {
// do something
}
}
现在,我迭代子节点并在任何时候返回一个节点,该节点的值与要比较的字符串部分匹配
func countMatchingChars(key string, node *Node) (int, *Node) {
count := 0
for e := node.childern.Front(); e != nil; e = e.Next() {
// Getting error when accessing e.Value.key
if c := MatchCount(e.Value.key, key); c > 0 {
return c, e.Value
}
}}
我得到以下错误
./trie.go:53: e.Value.key undefined (type interface {} has no field or method key)
./trie.go:54: cannot use e.Value (type interface {}) as type *Node in return argument: need type assertion
我得到了解决方案,并在go中发现了接口:)
./trie.go:53: e.Value.key undefined (type interface {} has no field or method key)
./trie.go:54: cannot use e.Value (type interface {}) as type *Node in return argument: need type assertion
if c := MatchCount(e.Value.(*Node).key, key); c > 0 {
return c, e.Value.(*Node)
}