Create a map of string to List

前端 未结 3 1949
小蘑菇
小蘑菇 2020-12-08 04:10

I\'d like to create a map of string to container/list.List instances. Is this the correct way to go about it?

package main

import (
    \"fmt\"         


        
相关标签:
3条回答
  • 2020-12-08 04:22

    there's nothing technically incorrect about what you've written, but you should define your own type around map[string]*list.List to avoid some pitfalls, like trying to call the .Front() method on a nil pointer. Or make it a map[string]list.List to avoid that situation. A list.List is just a pair of pointers and a length value; using a list.List pointer in your map just adds the extra case of a nil pointer on top of the case of an empty list. In either situation, you should define a new struct for this use case.

    I would be inclined to write it like this: http://play.golang.org/p/yCTYdGVa5G

    0 讨论(0)
  • 2020-12-08 04:28

    Whenever I've wanted to use a List I've found that a slice was the right choice, eg

    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])
    }
    
    0 讨论(0)
  • 2020-12-08 04:34

    My favorite syntax for declaring a map of string to slice of string:

    mapOfSlices := map[string][]string{
        "first": {},
        "second": []string{"one", "two", "three", "four", "five"},
        "third": []string{"quarter", "half"},
    }
    
    0 讨论(0)
提交回复
热议问题