A function is just a set of instructions with a name (although the name is optional)
The main
function is a special function - execution starts from here. For example
func main() {
fmt.Printf("Hello, World!")
}
You don’t explicitly call the main
function. For all other functions, you need to call them. This is how you would do it with another function
func PrintHello() {
fmt.Printf("Hello World!")
}
func main() {
PrintHello()
}
Function declaration - starts with func
keyword in Go
Use meaningful names for functions
Functions may need some input data to perform computation - so these are passed to the functions inside parantheses.
Parameters are listed in parantheses after the function name. For example,
func foo(x int, y int) {
fmt.Printf(x * y)
}
// calling the function
func main() {
foo(2, 3)
}
Arguments are supplied when you call the function.
Note the order of variable name and its type is different from Java.