Go Function Syntax 🎯

beginner
18 min

Go Function Syntax 🎯

Welcome to our deep dive into Go (Golang) functions! This lesson will guide you through the basics and advanced concepts of Go functions, helping you write clean and efficient code. Let's get started!

What are Functions? 📝

In programming, functions are blocks of code that perform specific tasks. They help organize your code, making it more modular and easier to manage. In Go, functions are first-class citizens, meaning they can be passed around and used as values.

Function Syntax 💡

A simple Go function looks like this:

go
func FunctionName(parameters) { // Function body }

Let's create a simple function that prints a greeting:

go
func Greet(name string) { fmt.Println("Hello, " + name) }

Here's what we've got:

  • func: This keyword indicates the start of a function definition.
  • Greet: This is the name of our function. Choose names that clearly describe what the function does.
  • (name string): These are the parameters of our function. In this case, we have one parameter called name of type string.
  • fmt.Println("Hello, " + name): This is the function body. It prints a greeting message with the provided name.

Function Calling ✅

To call a function, simply use its name followed by parentheses:

go
Greet("John")

Running this code will print: Hello, John

Function Return Types 📝

A function can return a value using the return statement. Here's an example of a function that calculates the area of a rectangle:

go
func RectArea(length, width float64) float64 { return length * width }

You can call this function and store the result:

go
area := RectArea(5, 10) fmt.Println("Area:", area)

This will output: Area: 50

Anonymous Functions 💡

Anonymous functions, also known as lambda functions, are functions without a name. They are useful when you need a function temporarily or want to pass a function as an argument to another function. Here's an example:

go
func ApplyFunction(x float64, f func(float64) float64) float64 { return f(x) } square := func(x float64) float64 { return x * x } result := ApplyFunction(4, square) fmt.Println("Square of 4:", result)

This code defines an anonymous function square and passes it as an argument to the ApplyFunction function. The output will be: Square of 4: 16

Quiz 💡

Quick Quiz
Question 1 of 1

What is the purpose of a function in programming?

Quick Quiz
Question 1 of 1

What is an anonymous function?