Sobes.tech
Junior — Middle

Kuidas tõhusalt salvestada objekte Map andmestruktuuri?

sobes.tech AI

Vastus AI-lt

In Go, to efficiently store objects in a data structure map, it is important to consider several aspects:

  • Keys should be of comparable types (e.g., strings, numbers, pointers). If the key is a complex type, such as a struct, it must be comparable.
  • Values can be of any type, including pointers to structs, which saves memory and avoids copying large objects.
  • To improve performance, pointers can be used in values so that large structs are not copied on each assignment.
  • Initialize the map with the necessary size if the approximate volume is known, to avoid frequent re-allocations.

Example:

// Define the struct
type User struct {
    ID   int
    Name string
}

// Create a map with string key and *User value
users := make(map[string]*User, 100) // pre-allocate memory

// Add a user
users["user1"] = &User{ID: 1, Name: "Alice"}

// Retrieve a user
user := users["user1"]
fmt.Println(user.Name) // Alice

Using pointers in values and pre-initializing the map improves the efficiency of object storage.