将引用的内部结构字段与go中的字符串类型进行比较

问题描述 投票:0回答:1

说我有两个定义链表的结构:

....
....

type node struct {
    item interface{}
    next *node
}

type LinkedList struct {
    first *node
    N int
}

...
...

并且我想比较基础节点的类型的值,例如,在一个查找函数中,在该函数中我们检查k == node.item是否满足以下条件:

func (l *LinkedList) find (key interface{}) bool {

    result := false
    if !l.isEmpty() {
        for x:= l.first; x != nil; x = x.next {
            if x.item == key {
                result = true 
                break
            }
        }
    return result
}

这对于预期的find函数不起作用,因为基础类型不同,因此func总是返回false。我们可以通过反映类型来确认这一点:

fmt.Println(reflect.TypeOf(key), reflect.TypeOf(x.item)) 
>>> string, *main.node

已尝试解决方法?

我已经尝试断言类型,但是这无法正常工作和出现紧急情况

tmp := x.item.(string)
>>>panic: interface conversion: interface {} is *main.node, not string

这种情况与使用fmt.Sprintf(x.item)相同

我对从这里去哪里有些困惑。有没有办法做到这一点?

向链接列表插入项目以下代码段应阐明如何处理插入]

func (l *LinkedList) insertFirst(item interface{}) {
    var first *node = new(node)
    oldfirst := l.first
    first.item = item
    first.next = oldfirst
    l.first = first
    l.N++
}

.....
//which gets called somewhere like
var n *node = new(node)
n.item = item
l.insertFirst(n)


.....wait no theres the error! 
----------

burak-serdar,您对我将节点插入节点100%正确!

pointers go struct types reference
1个回答
0
投票

find()中的接口比较是有效的比较,并且如果键的类型和节点中存储的值的类型相同,则它将起作用。但是,证据表明您添加了一个节点来代替值。

© www.soinside.com 2019 - 2024. All rights reserved.