Functions
In Go, a function is a block of code that performs a specific task. Functions help to modularize code, making it more readable and reusable.
To define a function, we use the func
keyword followed by the function name and parentheses. Inside the parentheses, we can specify parameters that the function can accept. The code block within every function starts with a curly brace ({) and ends with a curly brace (}).
Let's start with a simple function that prints a greeting message:
func greet() {
fmt.Println("Hello, world!");
}
func main() {
greet();
// Output: "Hello, world!"
Functions can also accept parameters, which allow us to pass values into the function for processing. Here's an example:
func greetWithName(name string) { fmt.Printf("Hello, %s! ", name); } greetWithName("Alice"); // Output: "Hello, Alice!" greetWithName("Bob"); // Output: "Hello, Bob!"
Functions can return values using the return
statement. This allows us to capture the result of a function and use it in our code. Here's an example:
func add(a, b int) int {
return a + b;
}
let result = add(3, 5);
fmt.Println(result); // Output: 8
Functions can have default parameter values, which are used if no argument is provided when the function is called. Here's an example:
func greetWithDefaultName(name string) {
if name == "" {
name = "world";
}
fmt.Printf("Hello, %s!
", name);
}
greetWithDefaultName(""); // Output: Hello, world!
greetWithDefaultName("Alice"); // Output: Hello, Alice!
We can also define functions that accept a variable number of arguments using the ...
syntax. Here's an example:
func addMultiple(nums ...int) int {
sum := 0;
for _, num := range nums {
sum += num;
}
return sum;
}
fmt.Println(addMultiple(1, 2, 3)); // Output: 6
fmt.Println(addMultiple(4, 5, 6, 7)); // Output: 22
The ...
syntax allows us to accept a variable number of arguments. Here's an example using a map for keyword arguments:
func printInfo(info map[string]interface{}) {
for key, value := range info {
fmt.Printf("%s: %v
", key, value);
}
}
printInfo(map[string]interface{}{"name": "Alice", "age": 30, "city": "New York"});
Functions are a fundamental part of Go programming, enabling us to create modular, reusable, and maintainable code. As we progress, we'll explore more advanced concepts and techniques related to functions.