Create a map of string to List slice

 

 

 

package main

import (
    "fmt"
    "container/list"
)

func main() {
    x := make(map[string]*list.List)

    x["key"] = list.New()
    x["key"].PushBack("value")

    fmt.Println(x["key"].Front().Value)
}

 

./hello 
value

 

package main

import (
    "fmt"
    "container/list"
)

func main() {
    x := make(map[string]list.List)

    x["key"] = list.New()
    x["key"].PushBack("value")

    fmt.Println(x["key"].Front().Value)
}

 

 

go build -o hello hello.go
# command-line-arguments
./hello.go:11:14: cannot use list.New() (type *list.List) as type list.List in assignment
./hello.go:12:13: cannot call pointer method on x["key"]
./hello.go:12:13: cannot take the address of x["key"]
./hello.go:14:25: cannot call pointer method on x["key"]
./hello.go:14:25: cannot take the address of x["key"]

 

 

package main
import (
"container/list"
"fmt"
)

func main() {
m := make(map[string]list.List)
fmt.Println("hello %s", m)
}

 

./hello 
hello %s map[]

 

 

package main

import "fmt"

func main() {
    x := make(map[string][]string)

    x["key"] = append(x["key"], "value")
    x["key"] = append(x["key"], "value1")

    fmt.Println(x["key"][0])
    fmt.Println(x["key"][1])
}

 

 

 
package main

import "fmt"

func main() {
    // Create map of string slices.
    m := map[string][]string{
        "cat": {"orange", "grey"},
        "dog": {"black"},
    }
    
    // Add a string at the dog key.
    // ... Append returns the new string slice.
    res := append(m["dog"], "brown")
    fmt.Println(res)
    
    // Add a key for fish.
    m["fish"] = []string{"orange", "red"}
    
    // Print slice at key.
    fmt.Println(m["fish"])
    
    // Loop over string slice at key.
    for i := range m["fish"] {
        fmt.Println(i, m["fish"][i])
    }
}
 
 

 

 

./hello 
[black brown]
[orange red]
0 orange
1 red

 

posted on 2021-07-13 16:13  tycoon3  阅读(54)  评论(0)    收藏  举报

导航