To create a function in Golang or Go, you have to write the keyword func
then the name of the function followed by the ()
symbol (opening and closing brackets). Inside the brackets, we can have the parameters with the type associated after that. After the brackets, you can write the type of the return value.
TL;DR
package main
import "fmt"
func main() {
// call the `sayGreeting` function
message := sayGreeting("John")
fmt.Println(message)
/*
OUTPUT:
John
Hello World
*/
}
// a simple function that accepts
// a parameter called `personName` of type string
// and returns the string `Hello World`
func sayGreeting(personName string) string {
fmt.Println(personName)
return `Hello World`
}
For example, let's say we have to create a function called sayGreeting
that returns the string
called Hello World
.
First, we can write the keyword func
followed by the name of the function, in our case sayGreeting
name.
It can be done like this,
package main
func main() {
}
// a simple function that
// returns the string `Hello World`
func sayGreeting() string {
return `Hello World`
}
To call the function, we can write the name of the function followed by the ()
symbol (opening and closing brackets) inside the main()
function.
It can be done like this,
package main
func main() {
// call the `sayGreeting` function
sayGreeting();
}
// a simple function that
// returns the string `Hello World`
func sayGreeting() string {
return `Hello World`
}
Now let's save the return value of the sayGreeting
function to a variable called message and then print it to the console using the Println()
method from the fmt
module.
It can be done like this,
package main
import "fmt"
func main() {
// call the `sayGreeting` function
message := sayGreeting()
fmt.Println(message)
/*
OUTPUT:
Hello World
*/
}
// a simple function that
// returns the string `Hello World`
func sayGreeting() string {
return `Hello World`
}
Till now we haven't used the function parameters, let's create a parameter called personName
with the type of string
and then print it before returning the Hello World
string.
It can be done like this,
package main
import "fmt"
func main() {
// call the `sayGreeting` function
message := sayGreeting("John")
fmt.Println(message)
/*
OUTPUT:
John
Hello World
*/
}
// a simple function that accepts
// a parameter called `personName` of type string
// and returns the string `Hello World`
func sayGreeting(personName string) string {
fmt.Println(personName)
return `Hello World`
}
We have successfully created a function in Golang or Go. Yay 🥳!
See the above code live in The Go Playground.
That's all 😃!