2015-04-02 157 views
0

我很好奇,爲什麼這DeepEqual支票是假的:Golang:reflect.DeepEqual返回false

package main 

import (
    "encoding/json" 
    "fmt" 
    "log" 
    "reflect" 
    "strings" 
) 

type Result struct { 
    Topic string `json:"topic,omitempty"` 
    Id int `json:"id,omitempty"` 
} 

// Result represents the returned collection from a topic search. 
type ResultResponse struct { 
    Result []Result `json:"results"` 
} 

func main() { 
    want := ResultResponse{ 
     []Result{{Topic: "Clojure", Id: 1000}}, 
    } 

    input := `{"results": [ {"topic": "Clojure", "id": 1000} ]}` 
    p := ResultResponse{} 

    err := json.NewDecoder(strings.NewReader(input)).Decode(&p) 

    if err != nil { 
     panic(err) 
    } 

    fmt.Println(p, want) 

    if !reflect.DeepEqual(input, want) { 
     log.Printf("returned %+v, want %+v", p, want) 
    } 


} 
+1

這是由於一個錯字:'如果嘗試!反映.DeepEqual(p,want)'。例如。 https://play.golang.org/p/LkYrawkjcU – 2015-04-02 21:41:15

回答

-2

DeepEqual返回false,因爲你要比較一個類型,是沒有可比性的兩個實例。 ResultResponse類型不具有可比性,因爲並非所有字段都具有可比性。 Result字段是切片,切片由語言指定爲不可比較的。

+2

不正確,問題是DeepEqual的第一個參數是'string'類型(可能是由於輸入錯誤)。 DeepEqual被記錄爲能夠處理切片和遞歸類型。 – 2015-04-02 21:44:08

0

我認爲這是一個編輯犯錯誤猜你想代碼是什麼:

"reflect.DeepEqual(p, want)" 

但實際上你寫道:

"reflect.DeepEqual(input, want)"