Home > Backend Development > Golang > What is the difference between mapped interface {} and type structure {}?

What is the difference between mapped interface {} and type structure {}?

WBOY
Release: 2024-02-06 09:00:05
forward
914 people have browsed it

What is the difference between mapped interface {} and type structure {}?

Question content

I just read that map[Type]interface{} specifies the mapping of keys of Type type, and its value is any, that is interface{}.

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

What is the difference between these two types of mapping?

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

Or what is the difference between map[type] interface{} which we define in a more general way?

We define each key-value pair through the structure?

Are these two methods just defining objects composed of key-value pairs?


Correct answer


Structure and mapping are different data structures. They have many differences. Here are just a few:

A structure has a fixed number of fields, which are declared once and cannot be changed.

3a15cefd8a1cc7ac8a7f27a0d3f9b13

The map can grow or shrink at runtime.

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

vector["z"] = 2.0
Copy after login

You can loop through map entries.

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

Structures do not support iteration (unless you use reflection).

Structure fields can have labels (additional attributes):

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

The map does not have this function.

The above is the detailed content of What is the difference between mapped interface {} and type structure {}?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template