Function Declaration
In the previous experiments, 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 int, 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 int, b int, c string, d string)(res1 int, res2 int, res3 string){}
// Short writing mode
func test(a, b int, c, d string)(res1, res2 int, res3 string){}
Now let's rewrite the program we mentioned earlier:
package main
import "fmt"
func check(a int) bool {
if a == 0 {
fmt.Println("The divisor cannot be 0")
return false
}
return true
}
func main() {
a1, b1 := 12, 4
a2, b2 := 12, 0
if check(b1) {
fmt.Println(a1 / b1)
}
if check(b2) {
fmt.Println(a2 / b2)
}
}
The result is as follows:
3
The divisor cannot be 0
Here, we extract the code that checks whether the divisor is 0 into a separate function called check
. When the divisor is 0, it outputs a corresponding prompt and returns false
, otherwise it returns true
. We only need to call the check statement when using it.