Go Go Functions! The Basics Of Functions (Go)

Hello World in Go

So far I’ve introduced Go with a “Hello World” and looked at the basics of variables. With today’s blog post I hope to take a look at the basics of functions within Go.

Go Go Functions! - A bad Inspector Gadget pun
Go Go Functions!

I am going to give examples of a few functions that I have learned and then in a future blog post expand on the concepts / build some example programs. I’m still learning Go so please bear with me.

A function is made up of:

func function_name() {

<CODE>

}

With func being a Go keyword. The main function is called upon when the Go code is compiled into an executable. Other functions can be automatically run by placing () at the end of the function, e.g.

func function_name(){

<CODE>

}()

Although this is something I am looking to write about later on when talking about concurrency. I’ve tried to comment my code where appropriate.

Date / Time

First up using some variables to hold today’s date (notetoday is the 26th November 2019, expect a different date if you use the below on a different date).

geektechstuff_go_time_func
A Date Function in Go
package main
import (
“fmt”
“time”
)
func main() {
varnow time.Time = time.Now()
varyearint= now.Year()
varmonth= now.Month()
varday= now.Day()
fmt.Println(“Today is”, day, “th”, month, year)
}
This imports the “fmt” and “time” modules so that the date can be read and then outputted.
Replacing Characters
Go replace characters in a string using the “strings” module.
geektechstuff_go_text_replace_func
String function to replace characters
package main
import (
“fmt”
“strings”
)
func main() {
string_pre:=”g$$kt$chstuff”
// string_pre contains a string that should say geektechstuff
replace:= strings.NewReplacer(“$”, “e”)
/* Created a variable called replace that calls on the “New Replacer” method from strings.
The first argument is the character that needs replacing and the second argument is what
it should be replaced with. So in this case $ should be replaced with e. */
string_post:= replace.Replace(string_pre)
// Another variable carries and contains the result from the replace.
fmt.Println(string_post)
// fmt.Println then outputs the contents of “string_post”
}
The above example takes g$$kt$chstuff and then returns geektechstuff.  The example uses the “New Replacer” method which belongs to the “Strings” package and is carried out on a value.
e.g.

replace:= strings.NewReplacer(“$”, “e”)

strings is a value. NewReplacer is a method which is tied to the value (in this case strings).

Receiving User Input

A function to read input in Go
A function to read input in Go

Go can be used to read input from an end user, in this case via a string of characters typed in on keyboard until the \n (enter / return) key is pressed. Before discussing this example I need to point out the the use of the _ (underscore) on the the line:

user_input, _ := input_method.ReadString(‘\n’)

geektechstuff_go_handling_multiple_value_output_variables
Using an underscore _ to drop a value

Unlike some programming languages, Go can return multiple values from an operation. The line user_input, _ := input_method.ReadString(‘\n’) is an example of this as it will return:

  • The characters the user typed
  • An error value

The characters the user typed are expected and wanted, even if the user typed garbage that does not equal a name. The error value is only wanted if an error has occurred. There are a few different ways to deal with the multiple value return.

Note: Do not define a variable for each return and not use the variable. As pointed out in my previous post, Go will not compile if the program contains unused variables.

Method One: The Underscore

Using an underscore _ will all the program to compile and from what I can tell Go just drops the value that should be outputted. It works, but from my readings it is messy and not the way most Go programmers would go.

Method Two: Defining and Using A Variable

The 2nd method is heading the correct way to what I believe most Go programmers would do but is not completely correct. The underscore _ is gone, the two returned values (user_input a.k.a. what the user typed and err a.k.a. the error value) are given variables to be placed into and both variables are used.

The problem here is that I have used fmt to output the err value, which when I have investigated further is frowned upon as a better way is available.

geektechstuff_go_func_error_handling_1
Handling an error incorrectly in Go

Method Three: Using Log

Go has a module called “log” that can be used in conjunction with error messages and seems to be the preferred method of handling an error.

Handling an error correctly in Go
Handling an error correctly in Go

But why “err != nil” you may ask. Well, this goes back to the multiple returned values. Even when it has a success Go will return an error value, which in the case of a success is “nil” so “!=” can be used to say:

If a value not-equal to nil is returned then log the value. If nil is returned then continue with the rest of the program.

With all the above in mind the code ends up looking like:

package main
import (
“bufio”
// Buffered Input/Output
“fmt”
// To output text
“os”
// To read input from the keyboard via the Operating System
)
func main() {
fmt.Println(“Enter name:”)
// Outputs a string to prompt the user to enter a name
input_method:= bufio.NewReader(os.Stdin)
// creates a buffered I/O to hold input from the Operating System’s Stdin (keyboard)
user_input, err:= input_method.ReadString(‘\n’)
// Reads a string of characters until the \n (Return or Enter key) is pressed
if err !=nil {
fmt.Println(“An error occured:”, err)
}
// Prints any errors to the screen
fmt.Println(“Hello”, user_input)
// Outputs a string saying Hello and whatever the user typed
}
Posted in Go

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.