Go:真值条件未执行

huangapple go评论114阅读模式
英文:

Go: truthy condition not executing

问题

我正在为我的一个应用程序使用neo4j。

在运行查询后,如果找到了值,result.Next()会返回一个bool值。

  1. var matches []int
  2. fmt.Println(result.Next(), "<== result NEXT ???") // 👨‍💻 this prints true
  3. if result.Next() {
  4. // 👍 for some reason this block won't run!
  5. fmt.Println("Assigning the values to the var")
  6. matches = result.Record().Values()[0].([]int)
  7. fmt.Println("Matches found", matches)
  8. }

我真的很感谢帮助,已经卡在这个问题上几个小时了。

英文:

I am using neo4j in for one of my applications.

After running a query if the values are found, result.Next() returns a bool

  1. var matches []int
  2. fmt.Println(result.Next(), &quot;&lt;== result NEXT ???&quot;) // &#128072; this prints true
  3. if result.Next() {
  4. // &#128071; for some reason this block won&#39;t run!
  5. fmt.Println(&quot;Assigning the values to the var&quot;)
  6. matches = result.Record().Values()[0].([]int)
  7. fmt.Println(&quot;Matches found&quot;, matches)
  8. }

I would really appreciate the help, stuck on it for hours

答案1

得分: 5

调用result.Next()将进入下一行。如果调用两次,将跳过一行。result.Next()不是幂等的!如果只有一个结果,在调用result.Next()后,第二次调用将永远不会返回true

如果您需要在多个位置检查result.Next()的结果,请将其存储在变量中:

  1. var matches []int
  2. hasNext := result.Next()
  3. fmt.Println(hasNext, "<== result NEXT ???")
  4. if hasNext {
  5. fmt.Println("Assigning the values to the var")
  6. matches = result.Record().Values()[0].([]int)
  7. fmt.Println("Matches found", matches)
  8. }

引用官方文档:消耗结果:

  1. for result.Next() {
  2. list = append(list, result.Record().Values[0].(string))
  3. }

如您所见,通过简单调用result.Next()来迭代结果。

英文:

Calling result.Next() proceeds to the next row. If you call it twice, you skip a row. result.Next() is not idempotent! If you have only a single result, calling result.Next(), the second call will never return true.

If you need to examine the result of result.Next() at multiple places, store it in a variable:

  1. var matches []int
  2. hasNext := result.Next()
  3. fmt.Println(hasNext, &quot;&lt;== result NEXT ???&quot;)
  4. if hasNext {
  5. fmt.Println(&quot;Assigning the values to the var&quot;)
  6. matches = result.Record().Values()[0].([]int)
  7. fmt.Println(&quot;Matches found&quot;, matches)
  8. }

Quoting from the offical docs: Consuming results:

  1. for result.Next() {
  2. list = append(list, result.Record().Values[0].(string))
  3. }

As you can see, results are iterated over by simply calling result.Next().

huangapple
  • 本文由 发表于 2022年1月16日 05:59:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/70725779.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定