1. Introduction
Go allows the creation of custom function types to enhance code readability and maintainability. By defining a custom function type, we can refer to a specific function signature with a new name, which can then be used to declare variables or parameters of that function type. Let’s walk through an example to illustrate how custom function types can be utilized in Go.
Definition
A custom function type in Go is defined using the type keyword, followed by a new type name and a function signature. This new type can then be used wherever a function with that signature is needed, improving code clarity.
2. Program Steps
1. Define a custom function type that represents a specific function signature.
2. Create a function that matches the custom function type's signature.
3. Declare a variable of the custom function type and assign the function created in step 2 to it.
4. Use the function variable to invoke the function.
3. Code Program
package main
import "fmt"
// Step 1: Define a custom function type
// binaryOp is a function type that takes two integers and returns an integer and an error.
type binaryOp func(int, int) (int, error)
// add is a function that matches the binaryOp function type signature.
func add(a, b int) (int, error) {
return a + b, nil
}
func main() {
// Step 3: Declare a function variable of the binaryOp type.
var op binaryOp
// Assign the 'add' function to the 'op' variable.
op = add
// Step 4: Use the function variable to invoke the function.
result, err := op(5, 7)
if err != nil {
fmt.Println("Operation failed:", err)
} else {
fmt.Printf("The sum of 5 and 7 is: %d\n", result)
}
}
Output:
The sum of 5 and 7 is: 12
Explanation:
1. package main - The package declaration for the executable program.
2. import "fmt" - Import statement for the Format package.
3. type binaryOp func(int, int) (int, error) - A custom function type binaryOp is defined with a function signature that takes two int arguments and returns an int and an error.
4. func add(a, b int) (int, error) - An add function is created that matches the signature of the binaryOp type.
5. In the main function, a variable op of type binaryOp is declared.
6. The add function is assigned to the op variable, demonstrating that functions can be treated as values in Go.
7. op(5, 7) - The op variable is then used to invoke the add function with arguments 5 and 7.
8. The result is checked for errors and printed out using fmt.Printf.
9. The output shows the successful addition of 5 and 7 resulting in 12.
Comments
Post a Comment