This is a creation in Article, where the information may have evolved or changed.
1. Start
I am a javaer, recent free time in study Golang.
Degree Niang, after installing the Go environment and liteide, I did not start from the foundation to look at the beginning, but want to change the existing Java project to be the Golang version.
Original Project content:
- The socket module receives data from the lower computer
- Parsing of Protocol data
- Parse the protocol data and store it in the database
- Web sub-project
Golang has a lot of handy features compared to Java. Especially the concurrency and the network aspect is the Golang selling point. So I went straight to a socket example and started to emulate the socket module that implemented the project.
2, the first program
Server.go:
PackageSocketImport("FMT" "NET" "Strings")funcStartServer () {Service: =": 3338"TCPADDR, err: = Net. RESOLVETCPADDR ("TCP4", service) CheckError (ERR) listener, err: = Net. LISTENTCP ("TCP", tcpaddr) checkerror (ERR) for{conn, err: = Listener. Accept ()ifErr! =Nil{Continue} FMT. Println ("New Connection:", Conn. Remoteaddr (). String ())GoHANDLECONN (conn)}}funcHANDLECONN (Conn net. Conn) { for{Buffer: = Make([]byte,1024x768) length, err: = conn. Read (buffer)ifErr! =Nil{Conn. Close ()}ifLength > A{data: = Buffer[:length]SwitchData[ One] &0Xff { Case0X80://TableFmt. Println ("Table") Case0X90://Chair Case0XA0://Table lamp default://Other}//Write Data //Conn. Write (data)} }}funcIsprotocol (data []byte)BOOL{if(Data[0]&0XFF) = =0XC0 && (data[Len(Data)-1]&0XFF) = =0xC1 {return true}return false}funcCheckError (err Error) {ifErr! =Nil{FMT. Println (Err. Error ())}}
Because it is the first note, it is also simple to say the basic grammar of Golang.
For a javaer, or a friend with a computer-based language, Golang's syntax doesn't look too difficult.
3. Package path
Like Java, we declare a package path for a program at first
packagesocket
Unlike Java, Golang's packages are not cascading. So for the convenience of identification we can also put all our projects under a parent package.
Like with Java, I've used a letus.xyz name here as the parent package (folder). So other programs can easily find the Server.go program to invoke.
If you want to build a program, both the package and the files within the package must be compiled in the correct order. The dependencies of a package determine the order in which they are built.
Source files that belong to the same package must all be compiled together, and a package is a unit at compile time, so according to convention, each directory contains only one package.
If a package is changed or recompiled, all client programs that reference the package must be recompiled.
4. Import of packages and libraries
import ( "fmt" "net" "strings")
Compared to Java, Golang uses this way to make the guide package and library look much more elegant.
Of course, you can also import as Java, one by one
import"fmt" import "net"import "strings"
Precautions:
If you import a package without using it, you will throw an error when building the program, such as imported and not Used:os, which follows the motto of Go: "No unnecessary code!" “。
When you import multiple packages, the order in which they are imported is sorted alphabetically.
If the package name is not a. or/start, such as "FMT" or "container/list", the go will be looked up in the global file, and if the package name starts with a./, then go will look in the relative directory, and if the package name starts with/begins (and can be used under Windows), it will be found in the absolute path of the system. 。
Importing a package is equivalent to all the code objects that contain the package.
In addition to the symbol _, the identifiers of all code objects in the package must be unique to avoid name collisions. However, the same identifiers can be used in different packages because they can be distinguished by using the package name.
5. Functions
After importing the packages and libraries, it is our program body. Of course, when we write the program must be after the package directly write the program body, and the packet and library is to use the content of this package to re-guide.
Golang, like C, is a process-oriented, functional programming, not an object-oriented one like Java.
func StartServer() {}func isProtocol(data []bytebool { returnfalse}func checkError(err error) {}
Visibility Rules:
When identifiers (including constants, variables, types, function names, structure fields, and so on) start with an uppercase letter, such as: Group1, an object using this form of identifier can be used by the code of the external package (the client program needs to import the package first), which is known as an export (as in object-oriented languages). public), identifiers are invisible to the package if they start with lowercase letters, but they are visible and available within the entire package (like private in an object-oriented language).
Basic structure of the function:
func functionName(parameter_list) (return_value_list) { …}
which
- Parameters: Parameter_list in the form of (param1 type1, param2 type2, ...)
- return type return_value_list in the form of (Ret1 type1, Ret2 type2, ...)
Golang's approach is more interesting than Java is that it allows multiple values to be returned. and its parameter representation is not the same as Java, the name is placed in front of the type.
6. Variables
":3338"
: = is a short declaration syntax that declares and assigns a value.
Or you can declare it with VAR:
var":3338"
Or
varstring":3338"
The short statement looks more elegant.
7. Constants
const ( Unknown = 0 Female = 1 Male = 2)
Our first program is useless to constants. Constants are defined by Const.
Definition Format for constants:
const identifier [type] =value
8. Basic data type
- Int,runes (Note: Rune is an alias of int)
- Int8, Int16, Int32, Int64
- Byte, Uint8, UInt16, UInt32, UInt64 (Note: Byte is the alias of Uint8)
- float32, float64 (no float type)
- bool
- String
- Complex128,complex64
9. Main function
package mainimport ( "letus.xyz/socket")func main() { socket.StartServer()}
Here we find the socket package through the absolute path LETUS.XYZ main package to invoke the program. Of course we can also import relative directories. Obviously, the way of relative paths is not conducive to the reuse of packets.
So personal advice to use absolute path to guide the package, after all, thinking and Java similar.
import ( "../socket")
10. Other
The Golang operator is basically the same as the Java control Structure statement, but it is worth mentioning that the Golang switch syntax supports string matching. This is a feature that Javaer often wants Java to provide as well.
switch field () () {case "time". Time ": V, _: = Time ( "2006-01-02 15:04:05" , s) field (Reflect (v))}