Ad space (banner)
๐ŸนGo Lessons
Lesson 6 / 68

Writing a Function

In this lesson you will learn the basic way to define a function in Go so you can reuse the same logic over and over. This is for anyone searching for "Go functions how to use".

You define a function with func name(param type) returnType { }. Bundling frequently used work under a name means you only have to call it to run it.

The sample code defines a greet function that takes a name string parameter and returns a greeting as a string. Like a recipe, once you have named a set of steps you can reproduce the same result whenever you need it - and change the arguments for a different one.

A common stumbling block for beginners is the order of the type annotations. Go writes paramName type and puts the return type after the function name, and that distinctive ordering takes some getting used to. You can also name the return values, which enables a shorthand where a bare return hands them back.

In real-world development, gathering shared logic into functions reduces duplication and means a fix only has to be made in one place.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)