Type Conversion
"Incompatible types for comparison" is the most common response for the errors when your codes contain things about "Conditional Branching" functions
Last updated
Was this helpful?
"Incompatible types for comparison" is the most common response for the errors when your codes contain things about "Conditional Branching" functions
Last updated
Was this helpful?
Before actually starting, let's discuss why the following codes don't work and output errors.
The output will be like the following picture:
The output will be like the following picture:
What's wrong with the codes? They seem that they have no problems!
As you can see, the errors are incompatible types for comparison
and wrong type for the value; expected string; got int
. The error message indicates that the type of the value is wrong for the function to use, but how can we fix it? Use the Type Conversion
functions!
Function
Description
json value
toByte "arg"
Function converts input to a slice of bytes - meaning []uint8. {{toByte "YAG€"}}
would output [89 65 71 226 130 172]
. toString
is capable of converting that slice back to string.
toDuration
toFloat
Converts argument (int or string type of a number) to type float64. Usage: (toFloat x)
. Function will return 0, if type can't be converted to float64.
toInt
Converts something into an integer of type int. Usage: (toInt x)
. Function will return 0, if type can't be converted to int.
toInt64
Converts something into an int64. Usage: (toInt64 x)
. Function will return 0, if type can't be converted to int64.
toRune "arg"
Function converts input to a slice of runes - meaning []int32. {{toRune "YAG€"}}
would output [89 65 71 8364]
. These two functions - the one above, are good for further analysis of Unicode strings. toString
is capable of converting that slice back to string.
toString
Has alias str
. Converts some other type into a string. Usage: (toString x)
.
To demonstrate toDuration
, outputs 12 hours from current time in UTC.
{{(currentTime.Add (toDuration (mult 12 .TimeHour))).Format "15:04"}}
is the same as{{(currentTime.Add (toDuration "12h")).Format "15:04"}}
or{{(currentTime.Add (toDuration 43200000000000)).Format "15:04"}}
To demonstrate json value
function.
Traverses given value
through MarshalJSON () and returns it as type string. For example {{json .TimeHour}}
outputs type string; before this .TimeHour
was of type time.Duration. Basically it's good to use if multistep type conversion is needed (toString (toInt value) )
and certain parts of cembed
need this for example. Example .
Converts the argument, number or string to type time.Duration. Number represents nanoseconds. String can be with time modifier (second, minute, hour, day etc) s, m, h, d, w, mo, y
,without a modifier string will be converted to minutes. Usage:(toDuration x)
. Example .