container/list
1 创建一个List对象来感受一下
l聽:=聽list.New() l.PushBack("one") l.PushBack(2) fmt.Println(l)
上面的代码可以得到如下的输出:
&{{0x2081a21b0聽0x2081a21e0聽<nil>聽?reflect.Value?}聽2}
这里具体的0x数据可能会变动,其实际记录的是对象的地址,但是最后的“2”不会变动,其表示当前的list对象里面有两个元素。
list.New()PushBack()interface{}
type聽Element聽struct聽{ //聽The聽value聽stored聽with聽this聽element. Value聽interface{} //聽contains聽filtered聽or聽unexported聽fields }
2.遍历list
上面的例子,仅仅用fmt.Println看到了list得简单的信息,那么若要遍历整个list怎么操作呢?来看代码:
l聽:=聽list.New() l.PushBack("one") l.PushBack(2) l.PushBack("three") for聽iter聽:=聽l.Front();iter聽!=聽nil聽;iter聽=聽iter.Next()聽{ 聽聽聽聽fmt.Println("item:",iter.Value) }
运行代码,我们可以看到结果:
item:聽one item:聽2 item:聽three
Front()Back()Next()iter !=nilValue
Len()indexat
3.修改list的成员
PushBack()PushFront()InsertAfter()InsertBefor
Remove()MoveAfter()MoveBefore()
我们来看一个实例。用这几个接口组合成一个Queue的实例:
type聽Queue聽struct聽{ 聽聽聽聽data聽*list.List } func聽NewQueue()聽*Queue聽{ 聽聽聽聽q聽:=聽new(Queue) 聽聽聽聽q.data聽=聽list.New() 聽聽聽聽return聽q } func聽(q聽*Queue)Enqueue(v聽interface{})聽{ 聽聽聽聽q.data.PushBack(v) } func聽(q聽*Queue)Dequeue()聽interface{}聽{ 聽聽聽聽iter聽:=聽q.data.Front() 聽聽聽聽v聽:=聽iter.Value 聽聽聽聽q.data.Remove(iter) 聽聽聽聽return聽v } func聽(q聽*Queue)聽Dump(){ 聽聽聽聽for聽iter:=q.data.Front();iter!=nil;iter=iter.Next()聽{ 聽聽聽聽聽聽聽聽fmt.Println("item:",iter.Value) 聽聽聽聽} } func聽main(){ 聽聽聽聽q聽:=聽NewQueue() 聽聽聽聽q.Enqueue("one") 聽聽聽聽q.Enqueue("two") 聽聽聽聽q.Dump() 聽聽聽聽v聽:=聽q.Dequeue() 聽聽聽聽fmt.Println("v:",v) 聽聽聽聽q.Dump() }
我们可以看到结果为:
item:聽one item:聽two v:聽one item:聽two
Init()