1. package import and export
In the GO language, package encapsulates a relatively independent function for external use. Package has the following features:
1.1 The package corresponds to a directory
This is similar to Java
1.2 The source code storage directory in the package is the last/end accuracy of the package, such as package math/rand. The source code is under the rand directory.
1.3 main is a special package name. Similar to the main function of Java, the executable program of GO must be in the main package.
1.4 The source code storage directory in the package is the last/end accuracy of the package, such as package math/rand. The source code is under the rand directory.
1.5 in the source code file, functions starting with an uppercase letter are exported (for external access ). This is similar to Java and access control, but it is too obscure.
However, functions starting with an underscore (_) in Python are internal functions, but external functions can still be accessed.
1.6 import package
Import "fmt"
Import "math/rand"
Import (
"Fmt"
"Mat/rand"
)
2. function
2.1 The function declaration can have no parameters, but the end of the function declaration must contain parentheses
This is not as flexible as Ruby. Function declarations and calls can be omitted in brackets. Python can also be omitted in a specific version, but later it was found that the code style is not uniform, so function declarations and calls without parentheses are certainly not supported in Python3.0.
Package main
Import "fmt"
Func main (){
Fmt. Println (add (42, 13 ))
}
2.2 function parameters and return value types are written at the end
This is completely different from Java and C, so it is easy to remember. Of course, there is no right or wrong, just get used to it.
Package main
Import "fmt"
Func add (x int, y int) int {
Return x + y
}
2.3 if the parameter types are the same, the preceding type declaration can be omitted. Only all the variable types before the last definition can be omitted.
Package main
Import "fmt"
Func add (int, y int) int {
Return x + y
}
2.4 Multiple values can be returned
This is required for advanced languages. Java and C do not support multiple return types. When an array is returned, the index is used to retrieve the array value as a devil number. This is really crazy!
Package main
Import "fmt"
Func swap (x, y string) (string, string ){
Return y, x
}
Func main (){
A, B: = swap ("hello", "world ")
Fmt. Println (a, B)
}
2.5 variables in the function body can be returned as function values in the function declaration.
Package main
Import "fmt"
Func split (sum int) (x, y int ){
X = sum * 4/9
Y = sum-x
Return
}
Func main (){
Fmt. Println (split (17 ))
}