How can I prevent the use of a card key type?

I have a type that can be used as a card key, but I want this to not happen. I suggested that if the type contains a private member, it will not be possible from other packages, but it seems to work anyway. What is the best way to make a type unusable as a card key?

type MyType struct {
    A *A
    b b

    preventUseAsKey ?
}
+4
source share
2 answers

. , , , .

: Spec: :

== != ; , , .

, , , . struct, struct:

, . , blank .

struct ( ), . , .

, .

, , , , :

type MyType struct {
    S             string
    i             int
    notComparable []int
}

MyType :

m := map[MyType]int{}

:

invalid map key type MyType

:

. : (- , ), , , :

p1, p2 := MyType{}, MyType{}
fmt.Println(p1 == p2)

:

invalid operation: p1 == p2 (struct containing []int cannot be compared)

, , . , -, ; , , :

type myType struct {
    S string
    i int
}

type MyType struct {
    myType
    notComparable []int
}

func main() {
    p1, p2 := MyType{}, MyType{}
    fmt.Println(p1.myType == p2.myType)
}

, MyType , - MyType .

+10

, .

,

. :

, , ; == .

, - , , , .
"" ( ):

type StringSliceWrap []string
type MyFunc func(i int)

.


2017: ( struct), , struct : . play.golang.org:

package main

// disallowEqual is an uncomparable type.
// If you place it first in your struct, you prevent == from
// working on your struct without growing its size. (Don't put it
// at the end; that grows the size of the struct)
type disallowEqual [0]func()

type T struct {
    _ disallowEqual
    Foo string
    Bar int
}

func main() {
    var t1 T
    var t2 T
    println(t1 == t2)
}

T !

+4

All Articles