go 中比较类型
go 中不可比较类型
slice、map、func
可否比较 是通过reflect.TypeOf(v1).Comparable() 进行判断
但是 如果真的想进行比较 可以通过 reflect.DeepEqual(v1, v2)
通过深度进行判断
// 举几个例子
// 方法 进行比较
package main
import (
"fmt"
"reflect"
)
func Equal(v1, v2 interface{}) {
comparable := reflect.TypeOf(v1).Comparable()
fmt.Println("comparable: ", comparable)
equal := reflect.DeepEqual(v1, v2)
fmt.Println("equal: ", equal)
return
}
func main() {
v1 := interface{}(func() {})
v2 := interface{}(func() {})
Equal(v1, v2)
//fmt.Println("equal: ", equal)
}
comparable: false
equal: false
// map package main import ( "fmt" "reflect" ) func Equal(v1, v2 interface{}) { comparable := reflect.TypeOf(v1).Comparable() fmt.Println("comparable: ", comparable) equal := reflect.DeepEqual(v1, v2) fmt.Println("equal: ", equal) return } func main() { v1 := interface{}(map[int]int{}) v2 := interface{}(map[int]int{}) Equal(v1, v2) //fmt.Println("equal: ", equal) } comparable: false equal: true
// slice package main import ( "fmt" "reflect" ) func Equal(v1, v2 interface{}) { comparable := reflect.TypeOf(v1).Comparable() fmt.Println("comparable: ", comparable) equal := reflect.DeepEqual(v1, v2) fmt.Println("equal: ", equal) return } func main() { v1 := interface{}([]int{}) v2 := interface{}([]int{}) Equal(v1, v2) //fmt.Println("equal: ", equal) } comparable: false equal: true
// slice 传递 具体的 值 package main import ( "fmt" "reflect" ) func Equal(v1, v2 interface{}) { comparable := reflect.TypeOf(v1).Comparable() fmt.Println("comparable: ", comparable) equal := reflect.DeepEqual(v1, v2) fmt.Println("equal: ", equal) return } func main() { v1 := interface{}([]int{1}) v2 := interface{}([]int{1,2}) Equal(v1, v2) //fmt.Println("equal: ", equal) } comparable: false equal: false
邮箱: 1090055252@qq.com