Go:真值条件未执行

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

Go: truthy condition not executing

问题

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

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

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

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

英文:

I am using neo4j in for one of my applications.

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

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

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

答案1

得分: 5

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

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

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

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

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

如您所见,通过简单调用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:

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

Quoting from the offical docs: Consuming results:

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

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:

确定