Sunday, 22 December 2013

Creating a function in golang

Our first piece of code had only one function - main. Let's create a new function in our code and call it from within the main function.
package main

import "fmt"

func helloWorld() {
    fmt.Println("Hello World")

func main() {
This piece of code does the same thing as our first hello world in go from the end user experience. The big difference is we are calling a function. Declaring a new function in go is simple - use the func keyword to begin declaring your function. Then, as in many other languages, include a pair of parentheses. Our hellWorld function takes no arguments at the moment so we leave the parentheses empty. Similarly, helloWorld doesn't return anything, so we can forget about giving our function a return type for the moment. Golang has some C inspired syntax so functions are enclosed in curly braces. The rest of the hellWorld function should look familiar since we are simply calling printing some text to standard out as we did before. Calling a function is equally familiar to anyone with some coding under their belt - as demonstrated in main above where we call our newly defined helloWorld func.

No comments:

Post a Comment