Syntax of a Golang function

Stefan M.
Golicious
Published in
2 min readMar 2, 2019

I already mentioned in my previous post that I wanted to explain the syntax of a func in a new blog… well, here we are.

The “basic” and simplest function looks like this:

func main() {}

I think I don’t have to explain more about it. This is a function without parameters and without a return value. This is basically the same as the main function in Kotlin. But the Kotlin version is obviously way shorter. They use just fun instead of func.

However. Most functions in the world have parameters. This is how it looks like in Golang:

func hello(name string) {}

The name of the variable begins followed by the type without any special chars between it. This is pretty cool in my opinion and is a bit different to Kotlin. They separate name and type with a colon between them.

More parameters can be added with a comma as separator of course.

When your function want to return a value (or more 😏) then you have to add this after the parentheses and before the curly brackets.

func swap(x string, y string) string {
return y + x
}

But what is really cool is that you can return as much values as you like. You can simply wrap the return values into parantheses too which indicates that these are all return values:

func returnALot() (string, int, bool) {
return "Golicious", 42, true
}

But wait — there is more! The return values can also be named and set inside the function without adding it to the return keyword 🤯:

func returnNamed() (name string, number int, boolean bool) {
name = "Golicious"
number = 42
boolean = true
return
}

But anyway. In all cases you need the return keyword. You can’t simply omit it in the last one.

Golang has a very handy syntax to consume these return values:

a,b,c := returnNamed()

This is a little bit similar to the destructuring declarations in Kotlin.
You can also ignore values with an underscore:

a,_,c := returnNamed()

In Kotlin we have visibility modifiers like private or protected (and public of course, but this is “hidden” by default). Golang has something similar. But it is implemented way easier in my opinion. It has only public and private — but without using this keywords. You define a func to be public when the first letter is in upper case! And when you write it in lower case its private. This is the reason why you write fmt.Println for example. The function Println is public accessible within the fmt package.

Learning sources

I learned this from the basic chapter from “A Tour of Go”. This site was also useful.

--

--