草庐IT

Golang : reflect. DeepEqual 返回 false

coder 2024-07-11 原文

我很好奇为什么这个 DeepEqual 检查是错误的:

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)
    }


}

最佳答案

这是我的案例:

func TestGoogleAccountRepository_FindByClientCustomerIds(t *testing.T) {
    type args struct {
        ids []int
    }
    tests := []struct {
        name    string
        args    args
        want    []cedar.GoogleAccount
        wantErr bool
    }{
        {
            name:    "should get client customer ids correctly",
            args:    args{ids: []int{9258066191}},
            want:    make([]cedar.GoogleAccount, 0),
            wantErr: false,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := googleAccountRepo.FindByClientCustomerIds(tt.args.ids)
            if (err != nil) != tt.wantErr {
                t.Errorf("GoogleAccountRepository.FindByClientCustomerIds() error = %v, wantErr %v", err, tt.wantErr)
                return
            }

            fmt.Printf("got = %#v, want = %#v\n", got, tt.want)
            if !reflect.DeepEqual(got, tt.want) {
                t.Errorf("GoogleAccountRepository.FindByClientCustomerIds() = %+v, want %+v", got, tt.want)
            }
        })
    }
}

当我第一次运行这个测试时,我收到以下消息:

load env vars from local fs env file
=== RUN   TestGoogleAccountRepository_FindByClientCustomerIds
--- FAIL: TestGoogleAccountRepository_FindByClientCustomerIds (0.62s)
=== RUN   TestGoogleAccountRepository_FindByClientCustomerIds/should_get_client_customer_ids_correctly
got = []cedar.GoogleAccount(nil), want = []cedar.GoogleAccount{}
    --- FAIL: TestGoogleAccountRepository_FindByClientCustomerIds/should_get_client_customer_ids_correctly (0.62s)
        googleAccount_test.go:64: GoogleAccountRepository.FindByClientCustomerIds() = [], want []
FAIL

注意这条信息:

GoogleAccountRepository.FindByClientCustomerIds() = [], want []

好像gotwant都是空slice吧?不,在我添加以下代码之后:

fmt.Printf("got = %#v, want = %#v\n", got, tt.want)

打印出来:

got = []cedar.GoogleAccount(nil), want = []cedar.GoogleAccount{}

如您所见,got 并不等于 want

那是因为我在 googleAccountRepo.FindByClientCustomerIds 方法中声明了 googleAccounts 变量,如下所示:

var googleAccounts []cedar.GoogleAccount

我改成之后

var googleAccounts = make([]cedar.GoogleAccount, 0)

测试通过:

=== RUN   TestGoogleAccountRepository_FindByClientCustomerIds
--- PASS: TestGoogleAccountRepository_FindByClientCustomerIds (0.46s)
=== RUN   TestGoogleAccountRepository_FindByClientCustomerIds/should_get_client_customer_ids_correctly
got = []cedar.GoogleAccount{}, want = []cedar.GoogleAccount{}
    --- PASS: TestGoogleAccountRepository_FindByClientCustomerIds/should_get_client_customer_ids_correctly (0.46s)
PASS

Process finished with exit code 0

关于Golang : reflect. DeepEqual 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29422602/

有关Golang : reflect. DeepEqual 返回 false的更多相关文章

  1. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  2. ruby - 默认情况下使选项为 false - 2

    这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb

  3. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  4. ruby - Ruby 中的隐式返回值是怎么回事? - 2

    所以我开始关注ruby​​,很多东西看起来不错,但我对隐式return语句很反感。我理解默认情况下让所有内容返回self或nil但不是语句的最后一个值。对我来说,它看起来非常脆弱(尤其是)如果你正在使用一个不打算返回某些东西的方法(尤其是一个改变状态/破坏性方法的函数!),其他人可能最终依赖于一个返回对方法的目的并不重要,并且有很大的改变机会。隐式返回有什么意义?有没有办法让事情变得更简单?总是有返回以防止隐含返回被认为是好的做法吗?我是不是太担心这个了?附言当人们想要从方法中返回特定的东西时,他们是否经常使用隐式返回,这不是让你组中的其他人更容易破坏彼此的代码吗?当然,记录一切并给出

  5. ruby-on-rails - ruby 日期方程不返回预期的真值 - 2

    为什么以下不同?Time.now.end_of_day==Time.now.end_of_day-0.days#falseTime.now.end_of_day.to_s==Time.now.end_of_day-0.days.to_s#true 最佳答案 因为纳秒数不同:ruby-1.9.2-p180:014>(Time.now.end_of_day-0.days).nsec=>999999000ruby-1.9.2-p180:015>Time.now.end_of_day.nsec=>999999998

  6. ruby - 从 String#split 返回的零长度字符串 - 2

    在Ruby1.9.3(可能还有更早的版本,不确定)中,我试图弄清楚为什么Ruby的String#split方法会给我某些结果。我得到的结果似乎与我的预期相反。这是一个例子:"abcabc".split("b")#=>["a","ca","c"]"abcabc".split("a")#=>["","bc","bc"]"abcabc".split("c")#=>["ab","ab"]在这里,第一个示例返回的正是我所期望的。但在第二个示例中,我很困惑为什么#split返回零长度字符串作为返回数组的第一个值。这是什么原因呢?这是我所期望的:"abcabc".split("a")#=>["bc"

  7. ruby - 为什么 Integer.respond_to?( :even? ) 返回 false? - 2

    我一直在研究RubyKoans,我发现about_open_classes.rbkoan很有趣。特别是他们修改Integer#even?方法的最后一个测试。我想尝试一下这个概念,所以我打开了Irb并尝试运行Integer.respond_to?(:even?),但令我惊讶的是我得到了错误。然后我尝试了Fixnum.respond_to?(:even?)并得到了错误。我还尝试了Integer.respond_to?(:respond_to?)并得到了true,当我执行2.even?时,我也得到了true。我不知道发生了什么。谁能告诉我缺少什么? 最佳答案

  8. ruby - Time.to_i 是否总是以 UTC 返回自 EPOCH 以来的秒数? - 2

    无论时间在哪个时区表示,时区差异是否总是被忽略?直觉上,对于那些使用UTC+2的人来说,从EPOCH开始经过的秒数应该更高。然而,事实并非如此。 最佳答案 Epoch基于utc时区https://en.wikipedia.org/wiki/Unix_time它与您当前所在的时区无关。 关于ruby-Time.to_i是否总是以UTC返回自EPOCH以来的秒数?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.

  9. ruby-on-rails - Ruby 流量控制 : throw an exception, 返回 nil 还是让它失败? - 2

    我在思考流量控制的最佳实践。我应该走哪条路?1)不要检查任何东西并让程序失败(更清晰的代码,自然的错误消息):defself.fetch(feed_id)feed=Feed.find(feed_id)feed.fetchend2)通过返回nil静默失败(但是,“CleanCode”说,你永远不应该返回null):defself.fetch(feed_id)returnunlessfeed_idfeed=Feed.find(feed_id)returnunlessfeedfeed.fetchend3)抛出异常(因为不按id查找feed是异常的):defself.fetch(feed_id

  10. ruby-on-rails - 如何让 Rails View 返回其关联的操作名称? - 2

    我有一个非常简单的Controller来管理我的Rails应用程序中的静态页面:classPagesController我怎样才能让View模板返回它自己的名字,这样我就可以做这样的事情:#pricing.html.erb#-->"Pricing"感谢您的帮助。 最佳答案 4.3RoutingParametersTheparamshashwillalwayscontainthe:controllerand:actionkeys,butyoushouldusethemethodscontroller_nameandaction_nam

随机推荐