Go to - use the map for its specified properties with user-defined types

I am trying to use the built-in map type as a set for my own type (Point, in this case). The problem is that when I assign a Point to a map and then create a new but equal point and use it as a key, the map behaves as if this key is missing on the map. Is this impossible to do?

// maptest.go

package main

import "fmt"

func main() {
    set := make(map[*Point]bool)

    printSet(set)
    set[NewPoint(0, 0)] = true
    printSet(set)
    set[NewPoint(0, 2)] = true
    printSet(set)

    _, ok := set[NewPoint(3, 3)] // not in map
    if !ok {
        fmt.Print("correct error code for non existent element\n")
    } else {
        fmt.Print("incorrect error code for non existent element\n")
    }

    c, ok := set[NewPoint(0, 2)] // another one just like it already in map
    if ok {
        fmt.Print("correct error code for existent element\n") // should get this
    } else {
        fmt.Print("incorrect error code for existent element\n") // get this
    }

    fmt.Printf("c: %t\n", c)
}

func printSet(stuff map[*Point]bool) {
    fmt.Print("Set:\n")
    for k, v := range stuff {
        fmt.Printf("%s: %t\n", k, v)
    }
}

type Point struct {
    row int
    col int
}

func NewPoint(r, c int) *Point {
    return &Point{r, c}
}

func (p *Point) String() string {
    return fmt.Sprintf("{%d, %d}", p.row, p.col)
}

func (p *Point) Eq(o *Point) bool {
    return p.row == o.row && p.col == o.col
}
+3
source share
1 answer
package main

import "fmt"

type Point struct {
    row int
    col int
}

func main() {
    p1 := &Point{1, 2}
    p2 := &Point{1, 2}
    fmt.Printf("p1: %p %v p2: %p %v\n", p1, *p1, p2, *p2)

    s := make(map[*Point]bool)
    s[p1] = true
    s[p2] = true
    fmt.Println("s:", s)

    t := make(map[int64]*Point)
t[int64(p1.row)<<32+int64(p1.col)] = p1
t[int64(p2.row)<<32+int64(p2.col)] = p2
    fmt.Println("t:", t)
}

Output:
p1: 0x7fc1def5e040 {1 2} p2: 0x7fc1def5e0f8 {1 2}
s: map[0x7fc1def5e0f8:true 0x7fc1def5e040:true]
t: map[4294967298:0x7fc1def5e0f8]

If we create pointers to two Points p1and p2with the same coordinates, they point to different addresses.

s := make(map[*Point]bool) , , Point, . , p1 p2 s, .

t := make(map[int64]*Point) , a Point, Point. , p1 p2 t, .

+2

Source: https://habr.com/ru/post/1785789/


All Articles