3

Newbee warning.

Can I make a map with a string key and "anything" as a value? The goal is to have a map of configuration data. This data can be either a single string (or boolean value or integer, but restricting this to a string is fine), or it can be an array of strings. Example: I'd like to store these items:

levels = 3
extra-directories = ["foo","bar","baz"]

The first option is always a single value (a string would be OK for me). The second option is zero or more values.

The goal is to have a single map where I can store these values and when looking at the map, I could use switch x.(type) to find out what the value is.

2 Answers 2

4

interface{} is a type that accepts any type.

conf := map[string] interface{} {
    "name": "Default",
    "server": "localhost",
    "timeout": 120,
}

conf["name"] is an interface{} not a string, and conf["timeout"] is an interface{} not an int. You can pass conf["name"] to functions that take interface{} like fmt.Println, but you can't pass it to functions that take string like strings.ToUpper, unless you know that the interface{}'s value is a string (which you do) and assert it's type:

name := conf["name"].(string)
fmt.Println("name:", strings.ToUpper(name))
server := conf["server"].(string)
fmt.Println("server:", strings.ToUpper(server))
timeout := conf["timeout"].(int)
fmt.Println("timeout in minutes:",  timeout / 60)

Another solution that might fit your problem is to define a struct:

type Config struct {
    Name string
    Server string
    Timeout int
}

Create configuration:

conf := Config{
    Name: "Default",
    Server: "localhost",
    Tiemout: 60,
}

Access configuration:

fmt.Println("name:", strings.ToUpper(conf.Name))
fmt.Println("server:", strings.ToUpper(cnf.Server))
fmt.Println("timeout in minutes:",  conf.Timeout / 60)
Sign up to request clarification or add additional context in comments.

1 Comment

Technically interface{} is an Interface that all types implement. It's a subtle distinction but worth mentioning.
1

Yes, you can do that using a map having type map[string]interface{}.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.