In this section, we're going to see how to parse string values to integer and float types.
Let's imagine that we have a variable called number
, which has 2
as a string. We're going to use strconv.ParseInt
and it returns two variables: the first one is the actual integer that we are expecting and the other is the return variable that arises if any error occurs during conversion.
If you look at the signature, you'll see that it returns integer 64
and an error:
So, the first thing we can do is check whether any error occurred during conversion; if it is not nil, we can understand that something happened and we'll type Error happened
.
Note
There's no try...catch
in Go, so you always have to do error checking if you want to write resilient code.
Now, for if
checking, we can give Success
as an output if the number is 2
. Now, let's run the described code as follows:
package main import ( "strconv" "fmt" ) func...