Functions in Go are declared with the func keyword:
func greet() {
fmt.Println("Hello, Go!")
}Call it with:
greet()func name(parameters) return_value_type {
// code block
}func add(a int, b int) int {
return a + b
}Types must be specified for each parameter, unless they are the same for all:
func multiply(x, y int) int {
return x * y
}Functions can return multiple values:
func name(paramters) (return_value_types) {
// code block
}Improve code readability and allows an implicit return using return without explicitly specifying values
Use ... to accept any number of arguments:
func sum(nums ...int) int {
total := 0
for _, num := range nums {
total += num
}
return total
}total := sum(1, 2, 3, 4)Functions can be assigned to variables or passed as arguments:
func sayHi() {
fmt.Println("Hi")
}
var f func() = sayHi // Defines f as a variable of type func(), and assigns the function definition sayHi
f() // call the function through variableAsk the AI if you need help understanding or want to dive deeper in any topic