加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

为什么元素和环结构为golang列表/环?

发布时间:2020-12-16 09:24:29 所属栏目:大数据 来源:网络整理
导读:为什么golang中的列表/环类型对单个项使用额外的结构元素/环而不是接口{}?我假设有一些好处,但我看不到它. 编辑:我的意思是询问api而不是在实现中使用Element / Ring.实现仍然可以使用非导出类型,但是api给出并接受接口{},那么为什么要让用户进出Element /
为什么golang中的列表/环类型对单个项使用额外的结构元素/环而不是接口{}?我假设有一些好处,但我看不到它.

编辑:我的意思是询问api而不是在实现中使用Element / Ring.实现仍然可以使用非导出类型,但是api给出并接受接口{},那么为什么要让用户进出Element / Ring?

Edit2:作为示例,Back()函数列表可能就像

func (l *List) Back() interface{} {
    if l.len == 0 {
        return nil
    }
    return l.root.prev.Value
}

列表仍然在内部使用Element,但它只是元素(未导出),因为它不会返回它,而只返回值.

解决方法

容器/列表是链表,因此让List结构可以作为一个整体在列表上运行并跟踪列表的开头和结尾是有益的.

由于它是链接列表,因此您希望能够将项目链接在一起并从一个项目导航到下一个项目或上一个项目.这需要一个结构,该结构保存指向下一个和前一个项目的指针,并允许您导航到这些项目(使用Next()和Prev()函数). Element结构用于此目的,它包含指向下一个/上一个项目的指针以及实际值.

这是结构的定义方式,它们也有各种成员函数

type List struct {
    root Element // sentinel list element,only &root,root.prev,and root.next are used
    len  int     // current list length excluding (this) sentinel element
}

type Element struct {
    // Next and previous pointers in the doubly-linked list of elements.
    // To simplify the implementation,internally a list l is implemented
    // as a ring,such that &l.root is both the next element of the last
    // list element (l.Back()) and the previous element of the first list
    // element (l.Front()).
    next,prev *Element

    // The list to which this element belongs.
    list *List

    // The value stored with this element.
    Value interface{}
}

容器/环没有你所暗示的“额外”结构.只有Ring结构将一个项链接到下一个/上一个项并且还保存该值. Ring没有开始/结束,因此不需要在整个环上运行结构或跟踪开始.

type Ring struct {
    next,prev *Ring
    Value      interface{} // for use by client; untouched by this library
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读