DEV Community

Kenny Grant for Project Page

Posted on

Just for func

If you missed the first episode of this series about Learning Go, you should start at the beginning (see the link above).

Today we're going to have fun with functions. First though, I must apologise for stealing the title of today's lesson from renowned gopher Francesc Campoy, who made a a really fun series of podcasts called Just for Func - once you're a little further along with Go, you should watch them all for another perspective on the language.

As well as looking at go functions today, we'll learn three new keywords:

  • const - a value that doesn't change
  • var - a value that may change
  • return - leave a function and give the caller some output

If you've used another language in the C family you'll probably be familiar with all of these. Let's start where we left off, with function main, but we'll try adding another function which we can call from main. We declare functions with the func keyword which we saw last time, and declare constants with const and variables with var (though often in Go this isn't necessary, as you'll see later).

We're going to define a function to find the position of a number in pi:

// piPosition finds the first location of a given number in pi
func piPosition(number int) int {
    ...
    return index
}

This uses func to declare a function called piPosition (note the camel case, that's what we use in Go), which takes a number of type int (integer), and returns an integer representing the index of this number in pi.

The full code is below or here - we declare a constant for pi (note there is no type assigned, this is implied) - you can read more about the reasons for allowing this on the go blog about constants.

We then declare an integer number, add one to it, skip past some commented out code (which is there to show you what you can't do - try uncommenting it and see what happens), and call the function piPosition. piPosition is an odd and rather useless little function which finds the index, but it'll show us how functions work in Go and how to use return. Inside piPosition, we convert both pi and number (53 in this case) to strings, and find the index of the number within pi (you can find most numbers within pi if you look long enough).

There's one interesting problem here though - if you choose to use the specifier %f within printf (to convert pi to a float), you'll get no result for 53, because pi will be truncated to the size of number that would fit into a float type. This tells us something interesting - the pi constant declaration turns it into something other than float.

// Package main compares strings
package main

// These are the packages imported by this program
import (
    "fmt"
    "strings"
)

// A constant cannot be changed during program execution
const pi = 3.141592653589793238462643383279502884

// the entry point for the program
func main() {

    // A variable stores a value that may change
    var number int = 52

    // We can change number, but not pi
    number = number + 1

    // This is a compile error, try uncommenting to see
    // go is a compiled language and will not allow you to
    // compile a program which does a Bad Thing like this
    // pi = 52

    // We also can't assign a string to a number, try this to see 
    // number = "string"

    // Let's call the function piPosition 
    // and assign its return value to index
    index := piPosition(number)

    // Print something with a format - see Printf for more details.
    fmt.Printf("The number %d is at position %d in pi", number, index)

}

// piPosition finds the index in pi 
// (as a string) of a given number
func piPosition(number int) int {
    // We're going to cheat and use strings
    p := fmt.Sprintf("%v", pi)
    n := fmt.Sprintf("%d", number)

    // A quick search in the standard library docs 
    // turns up this function to find the index in a string
    // let's return this as an answer from the function, 
    // using the return keyword
    return strings.Index(p, n)
}

Note when we call piPosition, we assign the result to a variable without using var, or even a type. This is how you can implicitly create new variables in Go, and it's handy so you'll see this a lot. The variable type is set by the return type of the function.

    // Let's call the function piPosition 
    // and assign its return value to index
    index := piPosition(number)

You can try out today's code here https://play.golang.org/p/h82XuiWFaJL - note the clever URL created as a hash (a unique string which maps to only this content). This is the sort of clever thing you'll learn to do later in the course, in order to impress your friends and confound your enemies.

Yes, I'm using fmt to convert numbers to strings, and comparing numbers as strings, experienced go programmers don't @ me :) You can also use the strconv package in the standard library for this, but I would like to keep things simple. If you work out why the %f specifier won't work, and what type pi ends up being, post it in the comments below - floating point numbers are notoriously tricky.

So to recap, we've covered these 6 keywords so far:

  • package - a folder containing go files
  • import - a way of importing go packages including the standard library
  • func - this stands for function, a set of instructions for transforming data
  • const - a value that doesn't change
  • var - a value that may change
  • return - leave a function and give the caller some output

Only 19 to go before you're an expert! In the next lesson we'll learn how to set up a web server in a few lines of code using the excellent Go standard library, and a few more keywords too, and we'll be on the way to making the next twitter something at 53words.com.

If you haven't already, you should download go and get set up locally with your editor - you can use this hello world exercise to test it out on your computer. I recommend VS Code as an editor on a Mac, but there are many other editors and most have go support. There are lots of instructions on the web for installation, I won't go into it here.

Top comments (0)