How do one convert string type to bool data type in Nim the best way ?
var u,o :string
o = "ooo"
if not u : # <- illusration only
How do one convert string type to bool data type in Nim the best way ?
var u,o :string
o = "ooo"
if not u : # <- illusration only
It totally depends on what you expect to be true and false, which is why Nim doesn't provide booleaness for strings by default. This is very similar to a question we had very recently at the forum about arrays: https://forum.nim-lang.org/t/8906.
Essentially you need to define yourself what true and false means for strings. Judging from the above I'm guessing that you might want if u.len != 0
. Note that strings in Nim can't be nil, so an uninitialized string is the same as an empty string. If you need to be able to tell uninitialized strings from initialized ones then you need to use the options
module.
You might be looking for converters: https://nim-lang.org/docs/manual.html#converters
Note that in Nim, doing so is discouraged and you should be using something along the lines of this:
let s = "abc"
if s != "":
# code here
You can use strutils.parseBool:
import strutils
let
a = "n"
b = "true"
if parseBool(a):
echo "a is true"
else:
echo "a is false"
if parseBool(b):
echo "b is true"
else:
echo "b is false"