Functions and Error Handling in Golang

DevOps with Erdenay
3 min readJan 20, 2021

Functions are our little machines, we give the values to functions and we take the result which is the we want to see.

For a first example we will send a value and we will check the result is even number or not.

In Golang, we are sending a value but we are having two answers back, in green line we are saying “i am sending a value and it is integer”. At the other orange line we are saying “give me an integer answer but if that input is wrong, send me an error!”. That part is so important to understand the relationship between inputs and outputs and Golang is so solid describing the error! Golang always saying “Okay you are sending me something but be aware always, you may have error always!”

green = input / orange = output side

And we are writing the check system for the even number stat. After “num / 2” procces if it’s result is not 0 and number is not an even number, for these situations we are writing our error message. Like we said before we are sending a value but we are having two values always and always!

And that “return 0” part goes for “(int,” and errors.New(“ERROR! That ..”) part goes for “error)” side. These parts for unexpected scenarios.
If user sends us correct values (even numbers) that if block wont work and we wont see any error messages and only that small “return num, nil” block will work.

This “return num,” will handle the “(int,” side and nil part will take that “error)” part. Nil(zero) means “my error is nothing” and we wont have any error message.

For a shortcut we can say green line is our input value. Orange lines are taking the charge of orange lines and blue lines are taking charge of blue lines.

Lets use that function in a main function. Here we are sending output of evenNum(10) to result variable and if we have error at that step, that error will be sent to err variable.

And now we will make it further and we will add some input steps for taking values from user. At that step we will take input from user but that input will be as string format so we should trim the space value on tha input and convert string value to integer value. Finally we should send that variable to our function.

You can reach to full of code from here
erdenayates/golang-function-error-input (github.com)

--

--