create a map with a value of type pointer in go

To create a map with a value of type pointer in Go, you can use the make function to create an empty map with the desired key and value types, and then set the values of the map to pointers to the desired type.

Here's an example:

main.go
type Person struct {
    Name string
    Age  int
}

func main() {
    // create an empty map with string keys and *Person values
    people := make(map[string]*Person)

    // create new Person objects, and store pointers to them in the map
    people["Alice"] = &Person{Name: "Alice", Age: 30}
    people["Bob"] = &Person{Name: "Bob", Age: 25}

    // access the pointers in the map to manipulate the Person objects
    people["Alice"].Age += 1
    people["Bob"].Name = "Robert"

    // print the updated values
    fmt.Println(people["Alice"])  // &{Alice 31}
    fmt.Println(people["Bob"])    // &{Robert 25}
}
615 chars
22 lines

In this example, we create a map people with keys of type string, and values of type *Person (a pointer to a Person struct). We then create two new Person objects, and store pointers to them in the map using their names as keys. Finally, we manipulate the Age and Name fields of the Person objects directly via their pointers stored in the map, and then print the updated values.

gistlibby LogSnag