iT邦幫忙

2022 iThome 鐵人賽

DAY 4
0

Map

Map是一種key-value的無序集合,key類似index,指向value。

定義方式如下

package main

import "fmt"

func main() {

	// 只定義
	var map1 = map[string]string{}
	map1["name"] = "Sam"
	fmt.Printf("map1:%v\n", map1)
    // map1:map[name:Sam]
    
    
	// 定義並賦值
	var map2 = map[string]string{"name": "Abbie"}
	fmt.Printf("map2:%v\n", map2)
    // map2:map[name:Abbie]
    
    
	// 使用make()函數定義
	map3 := make(map[string]string)
	map3["name"] = "Luke"
	fmt.Printf("map3:%v\n", map3)
    // map3:map[name:Luke]
    
}

Map刪除元素的用法如下

package main

import "fmt"

func main() {
	var m = map[string]string{}
	m["name"] = "Sam"
	m["age"] = "28"
	m["title"] = "Software Engineer"
	fmt.Printf("map的內容:%v\n", m)
    // map的內容:map[age:28 name:Sam title:Software Engineer]
    
	// 删除key=age
	delete(m, "age")
	fmt.Printf("map的內容:%v\n", m)
    // map的內容:map[name:Sam title:Software Engineer]
}

List

Golang container/list 裡面有提供list可以使用
資料結構是double linked list
用法如下:

package main

import (
	"container/list"
	"fmt"
)

func main() {

	// 定義list 也可以寫成 l := list.New()
	var l list.List
	fmt.Printf("l2:%v\n", l)

	// 在list最後放入元素1
	l.PushBack(1)

	// 在list首位放入元素2
	l.PushFront(2)

	// 遍歷list
	for i := l.Front(); i != nil; i = i.Next() {
		fmt.Println("value", i)
	} 
    // value &{0x140001061e0 0x14000106180 0x14000106180 2}
    // value &{0x14000106180 0x14000106210 0x14000106180 1}
    
    

	element := l.PushFront(3)

	// 宣告element變數後用InsertAfter將 Hi新增至 element之後
	l.InsertAfter("Hi", element)

	// 宣告element變數後用InsertBefore將 Hello新增至 element之前
	l.InsertBefore("Hello", element)

	// 遍歷list
	for i := l.Front(); i != nil; i = i.Next() {
		fmt.Println("value", i)
	}
    // value &{0x140001062a0 0x14000106180 0x14000106180 Hello}
    // value &{0x140001062d0 0x14000106300 0x14000106180 3}
    // value &{0x14000106210 0x140001062a0 0x14000106180 Hi}
    // value &{0x140001061e0 0x140001062d0 0x14000106180 2}
    // value &{0x14000106180 0x14000106210 0x14000106180 1}

    

	//  移除element
	l.Remove(element)
	// 遍歷list
	for i := l.Front(); i != nil; i = i.Next() {
		fmt.Println("value", i)
	}
    
    // value &{0x140001062d0 0x14000106180 0x14000106180 Hello}
    // value &{0x14000106210 0x14000106300 0x14000106180 Hi}
    // value &{0x140001061e0 0x140001062d0 0x14000106180 2}
    // value &{0x14000106180 0x14000106210 0x14000106180 1}


}

上一篇
Day3 Go Struct/Array/Slice
下一篇
Day5 interface
系列文
挑戰typescript+react+golang+graphql18
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言