Go: 3-2 Map 和字符串的一些操作

Map

m2 := make(map[string]int) // m2 == empty map var m3 map[string]int // m3 == nil fmt.Println(“m, m2, m3:“) fmt.Println(m, m2, m3) fmt.Println(“Traversing map m”) for k, v := range m { fmt.Println(k, v) }

fmt.Println(“Getting values”) courseName := m[“course”] fmt.Println(m["course"] =, courseName) if causeName, ok := m[“cause”]; ok { fmt.Println(causeName) } else { fmt.Println(“key ‘cause’ does not exist”) }

fmt.Println(“Deleting values”) name, ok := m[“name”] fmt.Printf(“m[%q] before delete: %q, %v\n”, “name”, name, ok)

delete(m, “name”) name, ok = m[“name”] fmt.Printf(“m[%q] after delete: %q, %v\n”, “name”, name, ok)


##### map的key
 - map使用hash表,必须可以比较相等
 - 除了slice,map和fuction的內建类型都可以做key
 - Struct类型不包含上述字段,也可以做key
 - 会在编译时检查
 
 
###### 寻找最长不含有重复字符的子串 (abcabcbb -> abc) rune

//视频提供的方法 比较繁琐,逻辑复杂,此方法更简洁 func lengthOfNonRepeatingSubStr(s string)int { lastOccured := make(map[rune]rune) for _ , ch := range []rune(s) { lastOccured[ch] = ch } return len(lastOccured) } ```

rune 相当于go的char
strings