Function Declaration
In the previous labs, regardless of whether the program was simple or complex, we only used the main
function for operations.
A program can only have one main
function, which is the entry point of the program. When we run the program, other functions are called and executed directly or indirectly within the main
function.
Now let's take a look at the syntax of functions:
func functionName(parameters...)(returnValues...){
code block
}
Here, the function name is used to identify the function. The following rules apply to the function name:
- It can consist of letters, numbers, and underscores. However, the first letter of the function name cannot be a number. For example,
func 3ab(){}
is not valid.
- When the first letter is uppercase, it can be referenced by code in external packages. When the first letter is lowercase, it can only be used within the package. This is similar to public and private functions.
The parameter list declares the number and type of parameters passed into the function:
-
The parameter list can be empty or contain multiple parameters.
-
Each parameter consists of a parameter name and a parameter type. For example, in the parameter list below, we declare two variables of the int
type.
func test(a, b int) (res int){}
The return value list is used to return the values needed after the function is executed:
-
The return value list is similar to the parameter list. The number of parameters can be any value.
-
Generally, the return list consists of variable names and variable types, and the variable name is optional.
-
If only one variable is returned and only the variable type is declared, the parentheses can be omitted. For example:
func test(a int, b string) int{}
When the parameter types are the same, we can use the short writing mode. The two functions below have the same functionality:
func test(a, b int, c, d string)(res1, res2 int, res3 string){}
// Short writing mode
func test(a, b int, c, d string)(res1, res2 int, res3 string){}
Replace the contents of func.go
with the following code:
package main
import "fmt"
func check(divisor int) bool {
if divisor == 0 {
fmt.Println("The divisor cannot be 0")
return false
}
return true
}
func main() {
a1, b1 := 12, 4
a2, b2 := 12, 0
// Use the check function before division
if check(b1) {
fmt.Println(a1 / b1)
}
if check(b2) {
fmt.Println(a2 / b2)
}
}
Run the program again:
go run func.go
You should see the same output:
3
The divisor cannot be 0
This time, the check logic is encapsulated in the check
function, making the code cleaner and more reusable.