深入了解Golang官方container/list原理

 更新时间:2023年08月03日 15:19:40   作者:ag9920  
在 Golang 的标准库 container 中,包含了几种常见的数据结构的实现,其实是非常好的学习材料,本文主要为大家介绍了container/list的原理与使用,感兴趣的可以了解一下

开篇

我们继续上一篇 解析 Golang 官方 container/heap 用法 学习 Golang 的标准库 container 中,包含的常见的数据结构的实现,今天的主角是 container/list。

container/list 封装了双向链表的实现,其实在面试中我们经常被问到如何实现一个双向链表,虽然并不难,但总会有边边角角的处理需要小心。今天,我们就来结合源码,思考一下官方的同学是怎么基于 Golang 设计出一个双向链表的实现。

container/list

list 是 Golang 一经推出就提供的能力,除了在 1.2 版本添加了 MoveAfter, MoveBefore 后,到目前为止就没有别的迭代了。这一套实现是稳定可靠的,而且源码不过 240 行,没有外部依赖,非常适合初学者练手。

我们来看看官方提供的使用示例:

import (
	"container/list"
	"fmt"
)
func main() {
	// Create a new list and put some numbers in it.
	l := list.New()
	e4 := l.PushBack(4)
	e1 := l.PushFront(1)
	l.InsertBefore(3, e4)
	l.InsertAfter(2, e1)
	// Iterate through list and print its contents.
	for e := l.Front(); e != nil; e = e.Next() {
		fmt.Println(e.Value)
	}
}

首先使用 list.New() 方法创建一个 List 对象,随后就可以按照链表的正常逻辑去添加,删除,移动 Element。最后不断从 l.Front() 拿到数据,并通过 Next() 迭代,就可以遍历链表,输出的结果如下:

1
2
3
4

整体来看,container/list 包封装了两个结构:

  • List: 一个双向链表
  • Element: 一个链表中的元素

提供的能力也可以满足大部分场景的需要:

下面我们来结合源码看看 Element 和 List 是怎么实现的。

Element

// Element is an element of a linked list.
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 any
}

Element 的定义很简单,包含了 4 个部分:

  • 指向前一个元素的指针;
  • 指向后一个元素的指针;
  • 当前元素所属的 List;
  • 存储在当前元素的值。
// Next returns the next list element or nil.
func (e *Element) Next() *Element {
	if p := e.next; e.list != nil && p != &e.list.root {
		return p
	}
	return nil
}
// Prev returns the previous list element or nil.
func (e *Element) Prev() *Element {
	if p := e.prev; e.list != nil && p != &e.list.root {
		return p
	}
	return nil
}

作为双向链表的节点,自然是需要有能力获取到前一个元素,以及后一个元素。不过注意,这里并不是直接 return e.next 或者 return e.prev

参考 Element 注释我们知道:

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

container/list 中的 List 本质是个环形结构(ring),包含的 root 节点,既是双向链表中最后一个元素的 next,也是第一个元素的 prev。

这个其实算法中很常见,本质是个 sentinel node,或者叫【哨兵节点】,从 List 使用者的视角看是感知不到这个 root 存在的。多这一个节点,可以有效的帮助我们,操作头结点和尾结点:

虚线框里的东西是真正存储数据的【节点】,root 不存放数据,只用于辅助我们实现这个双向链表。

所以,这儿就很好理解了,当我们实现 Next() 方法时需要校验,如果某个节点的 next 是 root,说明它就是最后一个了,所以应该返回 nil(使用者是感知不到 root 的),Prev() 方法也是同理。

List

// List represents a doubly linked list.
// The zero value for List is an empty list ready to use.
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
}
// Init initializes or clears list l.
func (l *List) Init() *List {
	l.root.next = &l.root
	l.root.prev = &l.root
	l.len = 0
	return l
}
// New returns an initialized list.
func New() *List { return new(List).Init() }
// Len returns the number of elements of list l.
// The complexity is O(1).
func (l *List) Len() int { return l.len }

有了前面 root 的推理,这里看 List 就容易多了,和预期一样,一个双向链表对外只需提供一个节点即可,使用者可以调用 List 的 API 接口进行插入,删除,调整顺序,获取元素。

这里 List 结构只包含一个 root 元素,并且维护了一个 len 变量,记录当前链表的长度。我们通过 New() 构建出的 List 对象,只包含 root 一个元素,所以它的 next 和 prev 都是自己。

获取头尾结点

// Front returns the first element of list l or nil if the list is empty.
func (l *List) Front() *Element {
	if l.len == 0 {
		return nil
	}
	return l.root.next
}
// Back returns the last element of list l or nil if the list is empty.
func (l *List) Back() *Element {
	if l.len == 0 {
		return nil
	}
	return l.root.prev
}

Front 和 Back 两个方法支持我们获取链表的【头结点】和【尾结点】,有了 root 节点的辅助,这一点也很容易。root 的下一个节点就是头,root 的前一个节点就是尾,看一下我们上面画的图大家就很容易理解了。

基础链表操作

这里我们来看几个底层的链表操作,这几个方法会支撑起来 container/list 对外的 API 实现:

insert

// insert inserts e after at, increments l.len, and returns e.
func (l *List) insert(e, at *Element) *Element {
	e.prev = at
	e.next = at.next
	e.prev.next = e
	e.next.prev = e
	e.list = l
	l.len++
	return e
}
// insertValue is a convenience wrapper for insert(&Element{Value: v}, at).
func (l *List) insertValue(v any, at *Element) *Element {
	return l.insert(&Element{Value: v}, at)
}

insert 方法接收 e, at 两个 Element 指针入参,它的语义是将 e 元素挂在 at 元素之后。这里的步骤拆解一下:

调整 e 的前驱和后继:

  • 让 e 的 prev 是 at;
  • 让 e 的 next 是 at 的 next。

调整 at 和 at 的 next 的指针,让 e 作为中间节点:

  • 让 e 的 prev(也就是 at)的 next 指向 e;
  • 让 e 的 next(也就是原来 at 的 next)的 prev 指向 e。

将当前的 List 赋值给 e 的 list,调整长度即可。

官方还提供了一个 insertValue 作为一个简单的装饰器,这样可以直接传入新节点的值即可,构造节点这一步在这个方法内发生。

remove

// remove removes e from its list, decrements l.len
func (l *List) remove(e *Element) {
	e.prev.next = e.next
	e.next.prev = e.prev
	e.next = nil // avoid memory leaks
	e.prev = nil // avoid memory leaks
	e.list = nil
	l.len--
}

删除节点很简单,其实就是上面 insert 的逆向操作,找到要删除的节点 e 的前驱和后继,让它的 prev 的 next 跳过它,指向更下一个节点,让它的 next 的 prev 也跳过它,指向更前一个节点即可。最后把 len 更新一下。

需要注意的是,很多同学会犯错误,觉得调整完前驱后继指针即可,但其实,按照 GC 语言的特性,虽然逻辑上这个双向链表已经没有 e 了,但你没有把 e 的 next 和 prev 指针清空,就会导致随后它们指向的元素有可能不会被垃圾回收,导致出现内存泄漏。

而内存泄露的问题在线上是很难快速排查的,所以官方也是增加了 e.next = nile.prev = nil 这样保证 GC 扫描的时候不会漏掉。

move

// move moves e to next to at.
func (l *List) move(e, at *Element) {
	if e == at {
		return
	}
	e.prev.next = e.next
	e.next.prev = e.prev
	e.prev = at
	e.next = at.next
	e.prev.next = e
	e.next.prev = e
}

move 和 insert 比较像,它的语义多一层,代表将 e 从原来位置挪走,放到 at 的后面。而 insert 是原先 e 不存在于这个链表,新加进来的。

所以,你会发现这里多了一步处理:

e.prev.next = e.next
e.next.prev = e.prev

这两行就是为了处理 e 原来所在位置的前驱和后继,让它们跳过 e,指向更前或更后的节点。

后面的 e 和 at 指针的调整和 insert 是完全对齐的,大家可以看一下。这里因为是 move,不是新增节点,所以也无需调整 len。

API 实现

有了上面三个基础能力:insert, remove, move。配合上 List 的 root 节点,我们就可以随心所欲在双向链表里进行操作了。这里封装的对外 API 很多,但都是基于上面我们提到的能力。

此处我们就不一一赘述了,大家感受一下即可:

// Remove removes e from l if e is an element of list l.
// It returns the element value e.Value.
// The element must not be nil.
func (l *List) Remove(e *Element) any {
	if e.list == l {
		// if e.list == l, l must have been initialized when e was inserted
		// in l or l == nil (e is a zero Element) and l.remove will crash
		l.remove(e)
	}
	return e.Value
}
// PushFront inserts a new element e with value v at the front of list l and returns e.
func (l *List) PushFront(v any) *Element {
	l.lazyInit()
	return l.insertValue(v, &l.root)
}
// PushBack inserts a new element e with value v at the back of list l and returns e.
func (l *List) PushBack(v any) *Element {
	l.lazyInit()
	return l.insertValue(v, l.root.prev)
}
// InsertBefore inserts a new element e with value v immediately before mark and returns e.
// If mark is not an element of l, the list is not modified.
// The mark must not be nil.
func (l *List) InsertBefore(v any, mark *Element) *Element {
	if mark.list != l {
		return nil
	}
	// see comment in List.Remove about initialization of l
	return l.insertValue(v, mark.prev)
}
// InsertAfter inserts a new element e with value v immediately after mark and returns e.
// If mark is not an element of l, the list is not modified.
// The mark must not be nil.
func (l *List) InsertAfter(v any, mark *Element) *Element {
	if mark.list != l {
		return nil
	}
	// see comment in List.Remove about initialization of l
	return l.insertValue(v, mark)
}
// MoveToFront moves element e to the front of list l.
// If e is not an element of l, the list is not modified.
// The element must not be nil.
func (l *List) MoveToFront(e *Element) {
	if e.list != l || l.root.next == e {
		return
	}
	// see comment in List.Remove about initialization of l
	l.move(e, &l.root)
}
// MoveToBack moves element e to the back of list l.
// If e is not an element of l, the list is not modified.
// The element must not be nil.
func (l *List) MoveToBack(e *Element) {
	if e.list != l || l.root.prev == e {
		return
	}
	// see comment in List.Remove about initialization of l
	l.move(e, l.root.prev)
}
// MoveBefore moves element e to its new position before mark.
// If e or mark is not an element of l, or e == mark, the list is not modified.
// The element and mark must not be nil.
func (l *List) MoveBefore(e, mark *Element) {
	if e.list != l || e == mark || mark.list != l {
		return
	}
	l.move(e, mark.prev)
}
// MoveAfter moves element e to its new position after mark.
// If e or mark is not an element of l, or e == mark, the list is not modified.
// The element and mark must not be nil.
func (l *List) MoveAfter(e, mark *Element) {
	if e.list != l || e == mark || mark.list != l {
		return
	}
	l.move(e, mark)
}
// PushBackList inserts a copy of another list at the back of list l.
// The lists l and other may be the same. They must not be nil.
func (l *List) PushBackList(other *List) {
	l.lazyInit()
	for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() {
		l.insertValue(e.Value, l.root.prev)
	}
}
// PushFrontList inserts a copy of another list at the front of list l.
// The lists l and other may be the same. They must not be nil.
func (l *List) PushFrontList(other *List) {
	l.lazyInit()
	for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() {
		l.insertValue(e.Value, &l.root)
	}
}

比如我们有的时候需要插入元素,但希望放到某个节点之前,这个时候类似 InsertBefore 的处理,直接拿到目标节点的 prev,插到它的 prev 之后,本质上不就是放到了它之前了么?

l.insertValue(v, mark.prev)

这里的代码都不复杂,建议大家有需要的时候对照实现简单了解即可。

完整示例

有了上面的源码解析,我们来看看怎样实用,这里我们附上了链表的状态。从使用者的角度无需关心 root,其实还是很简单基础的链表能力,大家可以尝试阅读理解一下下面的调用结果:

package main
import (
    "container/list"
    "fmt"
)
func main() {
    l := list.New()
    l.PushBack("a")
    printList(l) // a
    l.PushBack("b")
    printList(l) // a b
    l.PushFront("c")
    printList(l) // c a b
    fmt.Println(l.Front().Value) // c
    fmt.Println(l.Back().Value)  // b
    fmt.Println(l.Len())         // 3
    l.MoveToBack(l.Front())
    printList(l) // a b c
    l.MoveToFront(l.Back())
    printList(l) // c a b
    l.Remove(l.Back())
    printList(l) // c a
}
func printList(l *list.List) {
    for e := l.Front(); e != nil; e = e.Next() {
        fmt.Print(e.Value, " ")
    }
    fmt.Println()
}

遍历链表也很简单,不断从 front 拿到元素,赋值为 Next,持续下去,直到 Next 为 nil,说明遍历结束,参照这里的 printList 即可。

结语

其实 container/list 不仅仅给我们展示了一个比较规范标准的双向链表实现,而且也广泛应用于很多业务场景,比如经典的 groupcache 底层的 LRU 就是依靠 container/list 的能力,我们下一篇文章会分析一下。

以上就是深入了解Golang官方container/list原理的详细内容,更多关于Golang container/list的资料请关注脚本之家其它相关文章!

相关文章

  • GoLang内存泄漏原因排查详解

    GoLang内存泄漏原因排查详解

    内存溢出是指程序在申请内存时,没有足够的内存空间供其使用,简单点说就是你要求分配的内存超出了系统能给你的,系统不能满足需求,于是产生溢出出现out of memory异常
    2022-12-12
  • Go 使用xorm操作mysql详情

    Go 使用xorm操作mysql详情

    这篇文章主要介绍了Go 使用xorm操作mysql详情,golang orm 库 xorm 的使用和项目结构。更多详细neural,需要的小伙伴可以参考下面文章内容
    2022-01-01
  • Golang处理gRPC请求/响应元数据的示例代码

    Golang处理gRPC请求/响应元数据的示例代码

    前段时间实现内部gRPC框架时,为了实现在服务端拦截器中打印请求及响应的头部信息,便查阅了部分关于元数据的资料,因为中文网络上对于该领域的信息较少,于是在这做了一些简单的总结,需要的朋友可以参考下
    2024-03-03
  • golang代码中调用Linux命令

    golang代码中调用Linux命令

    本文主要介绍了golang代码中调用Linux命令,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-02-02
  • Golang实现自定义recovery中间件

    Golang实现自定义recovery中间件

    在 Golang 的 Web 项目中,自定义 recovery 中间件是一种常见的做法,用于捕获并处理应用程序的运行时错误,下面我们就来看看具体如何实现吧
    2023-09-09
  • go语言编程实现递归函数示例详解

    go语言编程实现递归函数示例详解

    这篇文章主要为大家介绍了go语言编程实现递归函数示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • 解决Goland中利用HTTPClient发送请求超时返回EOF错误DEBUG

    解决Goland中利用HTTPClient发送请求超时返回EOF错误DEBUG

    这篇文章主要介绍了解决Goland中利用HTTPClient发送请求超时返回EOF错误DEBUG,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12
  • 使用go实现删除sql里面的注释和字符串功能(demo)

    使用go实现删除sql里面的注释和字符串功能(demo)

    这篇文章主要介绍了使用go实现删除sql里面的注释和字符串功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-11-11
  • Go语言使用buffer读取文件的实现示例

    Go语言使用buffer读取文件的实现示例

    本文主要介绍了Go语言使用buffer读取文件的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • golang动态库(so)生成与使用方法教程

    golang动态库(so)生成与使用方法教程

    这篇文章主要给大家介绍了关于golang动态库(so)生成与使用的相关资料,我们平时使用的动态库都是由c/c++开发最后生成的.so文件,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2023-07-07

最新评论