- read

GO from zero to hero — 7. Functions.

astrx.dev 1

Part 7: Functions in Go

In Go, a function is a block of code that performs a specific task. Just like how you use your tools to accomplish specific tasks on your spaceship, you use a function to perform a specific task in your program.

Functions can take inputs, perform operations on them, and produce outputs. Think of it like a machine that takes inputs and produces outputs based on the operations it performs.

Photo by Victoria Shes on Unsplash

Think of a coffee machine on your spaceship, you provide input (coffee powder, sugar, water, milk, and whatever you take with coffee) and ask it to perform a task (make cappuccino or espresso) and, the machine gives you back your drink based on it’s understanding of how to make coffee.

For the end-user, how coffee machine works can be a mystery, but if you are the one who makes a coffee machine, you need to know what’s going on and how. Let’s see how. Not how to build coffee machines, how to write functions like these in golang.

1. Defining a function

In Golang, a function is a set of instructions that perform a specific task. You can define a function using the keyword func, followed by the function name, parameters (if any), and return type (if any). Here's an example of a function that prints a message:

func greet(name string) {
fmt.Printf("Hello, %s!\n", name)
}

In this example, the function name is greet, and it takes a parameter of type string called name. The function uses fmt.Printf() to print a message, with the parameter name as part of the message.

2. Calling a function

Once you have defined a function, you can call it from other parts of your code. To call a function, simply use its name and provide any required arguments. Here’s an example of calling the greet function we defined earlier:

func main() {
greet("John")
}

In this example, we call the greet function and pass in the argument "John". This will print the message "Hello, John!".

3. Returning values from a function

Functions can also return values. To do this, you need to specify the return type in the function definition. Here’s an example of a function that returns a string:

func planetMessage(planet string) string {
return fmt.Sprintf("Greetings from planet %s!", planet)
}

In this example, the function takes a parameter of type string called planet. It uses fmt.Sprintf() to create a message that includes the planet name, and then returns the message as a string.

4. Using multiple return values

Golang allows functions to return multiple values. To do this, you simply need to specify multiple return types separated by commas. Here’s an example of a function that returns the name and distance of a planet:

func planetDistance(planet string) (string, float64) {
var distance float64
switch planet {
case "Mercury":
distance = 0.39
case "Venus":
distance = 0.72
case "Earth":
distance = 1.00
case "Mars":
distance = 1.52
default:
distance = -1.0
}
return planet, distance
}

func main() {
planet, distance := planetDistance("Mercury")
fmt.Println(planet, " is at distance of ", distance, " from earth")
}

In this example, the function takes a parameter of type string called planet. It uses a switch statement to set the distance variable based on the planet name. The function then returns two values: the planet name and the distance as a float64.

5. Using named return values

In Golang, you can also give names to the return values in a function definition. This can make the code more readable and can also help with documentation. Here’s an example of a function that uses named return values:

func planetGravity(planet string) (gravity float64) {
switch planet {
case "Mercury":
gravity = 3.7
case "Venus":
gravity = 8.87
case "Earth":
gravity = 9.81
case "Mars":
gravity = 3.71
}
return
}

func main() {
gravity := planetGravity("Mars")
fmt.Println("Gravity of mars is ", gravity)
}

Notice that a return command is still required although you no longer have to specify the variable you want to return, simply because it’s already known in the function signature.

6. Variadic functions

In Go, a variadic function is a function that can accept an arbitrary number of arguments of a specified type. This means that you can pass in as many arguments as you want and Go will automatically create a slice with those arguments for you.

func describeSpaceships(names ...string) string {
var message string
message = "These are the spaceships in our fleet: "
for _, name := range names {
message += name + ", "
}
return message
}

In this example, the describeSpaceships function takes in a variadic argument of type string with the parameter names. Inside the function, we create a new message variable and initialize it with a string describing the purpose of the message. We then loop through each name in the names slice and add it to the message. Finally, we return the message.

func main() {

message := describeSpaceships(
"USS Enterprise", "Millennium Falcon", "Serinity",
)
fmt.Println(message)
}

// Output :
// These are the spaceships in our fleet: USS Enterprise, Millennium Falcon, Serinity,

Previous: Maps, Part 6

Code.Share.Prosper.