This is a creation in Article, where the information may have evolved or changed.
Start with Golang's HelloWorld program.
Files: helloworld.go
" FMT " Func Main () { fmt. Println ("HelloWorld")}
Execute command: Go run helloworld.go, the program executes, output: Hello world.
1, go code is the package to organize the code, package similar to other languages in the library or module, and Java package concept is very similar to, a package under one or more. Go source files, a package is a folder, the name of the folder describes the role of the package.
2, the above is a simple go program, the following with a slightly complex structure to illustrate the main composition of Go program
Package Mainimport ("FMT" "Math" "StrConv" " Time") Type Userstruct{userNamestring AgeintBorth time. TIME}Const(HEIGHTint=1SIZEint=TenPI float64=Math. Pi)varCitystringvarCountrystringFunc Main () {User:= &user{username:"xiaoming", Age: A, Borth:time. Now ()} FMT. Println (showname (user)) Fmt. Println ("Hello World") fmt. Println (PI)}func showname (user*user)string { ifuser = =Nil {return "Null" } returnUser.username +"_"+StrConv. Formatint (Int64 (user.age),Ten) +"_"+User.borth.Format ("2006-01-02 15:04:05")}
(1) The package is used to declare the packages to which the source code belongs
(2) Import statement must follow the package statement, used to import the source code in the need to reference the other packages name, the imported package must be used, or the compilation will be error
(3) followed by the types (type), variables (VAR), constants (const), and Functions (func) that make up the program, and most of the cases, the order of the declarations is not required
3. About functions
A function consists of a func keyword, a function name, a list of arguments, a list of return values, and a function body enclosed in curly braces.
Parameter list, return value list can be empty
Go supports multi-valued returns, such as:
Func Sumandcount (age []intint) { return1}
Note: The ' {' opening parenthesis in Golang cannot be another line.
4. About main package and main function
The main package is special, it is used to define a stand-alone executable program, not a library, in the main package, the main function is also special, it is where the execution of the program begins.