gostructinterface

What's the difference between map[type] interface{} and type struct {}?


I just read that map[Type]interface{} specifies a map of keys of type Type with values any i.e. interface{}.

Isn't this almost the same as defining a structure i.e. type Name struct{ key1; value1, ...., keyn: valuen}?

What is the difference between those two types of mappings?

I read https://www.digitalocean.com/community/tutorials/how-to-use-json-in-go but I still don't get the difference.

Or is the difference that with map[type] interface{} we define in a more general way?

And with struct we define each key value pair?

And both of them are just ways to define objects which consist of key value pairs?


Solution

  • Structs and maps are different data structures. They have many differences. Here are just a few:

    A struct has a fixed number of fields that are declared once and can't change.

    point := struct{ x, y float64 }{
        x: 1.0,
        y: 1.0,
    }
    

    A map can grow or shrink at runtime.

    vector := map[string]float64{
        "x": 2.0,
        "y": 2.0,
    }
    
    vector["z"] = 2.0
    

    You can loop over map entries.

    for key, val := range vector {
        fmt.Println(key, val)
    }
    

    Structs don't support iteration (unless you use reflection).

    Struct fields can have tags (additional attributes):

    type User struct {
        Name          string    `json:"name"`
        Password      string    `json:"password"`
    }
    

    Maps don't have this feature.