Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

nim lang - Why same strings are not equal in Nim?

The string generated by the JSON package is not equal to the same looking string, why?

The last equality check in code below is false, why? playground

import strformat, json

type Price = tuple[price: float, currency: string]

func `%`*(v: Price): JsonNode = %(fmt"{v.price} {v.currency}")

let v: Price = (214.05, "USD")
let s: string = (%(v)).pretty

echo s                  # => "214.05 USD"
echo s == "214.05 USD"  # => false, why?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The echo proc can sometimes be deceptive in terms of representing strings, so I prefer to throw in the repr proc which makes sure to represent strings (and other objects) in a more clear way. See the output I get when I add the following lines to the example, representing both sides of the comparison:

echo repr(s)
echo repr("214.05 USD")
==>
0x105f5c0b8""214.05 USD""
0x105f1cf70"214.05 USD"

Through this representation we can see the strings are really not equal. Your % proc formats the contents of the Price tuple as a space separated string node, and the JSON pretty proc converts that string node to its JSON representation, which includes double quotes. Thus, to make the last comparison equal we need to write it like this:

echo s == ""214.05 USD""

Another possibility would be to write the comparison accessing the JsonNode.str variant field, which avoids involving the mischievous pretty:

echo (%(v)).str == "214.05 USD"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...