0
0
Goprogramming~15 mins

Function declaration in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Function declaration
📖 Scenario: You are creating a simple calculator program in Go that can add two numbers.
🎯 Goal: Build a Go program that declares a function to add two integers and then uses it to show the result.
📋 What You'll Learn
Declare a function named add that takes two int parameters and returns their sum as int.
Call the add function with two numbers.
Print the result of the addition.
💡 Why This Matters
🌍 Real World
Functions help organize code into reusable blocks, just like recipes in cooking. You can use them to perform tasks many times without rewriting code.
💼 Career
Knowing how to declare and use functions is essential for any software developer. It helps write clean, maintainable, and reusable code.
Progress0 / 4 steps
1
Create two integer variables
Create two integer variables called a and b with values 5 and 7 respectively.
Go
Hint

Use := to declare and assign variables in Go.

2
Declare the add function
Declare a function named add that takes two int parameters named x and y and returns their sum as int.
Go
Hint

Use func add(x int, y int) int to declare the function and return x + y to return the sum.

3
Call the add function
Inside main, call the add function with a and b and store the result in a variable called result.
Go
Hint

Use result := add(a, b) to call the function and save the sum.

4
Print the result
Print the value of the variable result using fmt.Println.
Go
Hint

Use fmt.Println(result) to print the sum.