Skip to content

Latest commit

 

History

History
111 lines (80 loc) · 2.6 KB

File metadata and controls

111 lines (80 loc) · 2.6 KB

22) Functions

Linkedin Follow X Follow
Interactive Learning


Functions

A function is a block of code that performs a specific task.

You have already been using one function: main. It is the entry point of every Go program.

You can create your own functions to organize and reuse code.

How to Declare a Function

Use the func keyword to declare a function:

func greet() {
    fmt.Println("Hello")
}

Here is the breakdown of the code:

  • func → keyword to declare a function
  • greet → name of the function
  • () → parentheses for parameters (empty here)
  • { } → body of the function

How to Call a Function

To execute a function, call it by its name followed by parentheses:

func main() {
    greet()
}

Functions with Return Values

A function can return a value using the return keyword.

You must specify the return type after the parentheses:

func getLanguage() string {
    return "Go"
}

Here is the breakdown of the code:

  • string → the return type
  • return "Go" → the value returned to the caller

To use the returned value:

language := getLanguage()
fmt.Println(language) // Go

Example Code

There are some function declarations in main.go file.

But they are incomplete.

Fix the Code

Open main.go file and complete the code lines.

Then validate your code by running:

go run topic.go 22 validate

✅ If everything is ok, you should see:

OK!

Conclusion

Now you know how to declare and call functions in Go.

Continue to the next topic 👇

Arguments ⮕️