Key Go Aspects
摘要
This chapter examines the Go programming language in more depth, covering many key aspects of the language. It includes examples comparing Go to Java, illustrating their similarities and differences. Like in Java, at the most basic level, Go source is a stream of characters often viewed as a sequence of lines. Go files are written (as is typically true in Java) in UTF-8 encoding. Go does not have a preprocessor like Java has to process Unicode escapes into raw characters; all Unicode characters are treated the same, and escapes can only appear inside of string or character literals, not in identifiers or elsewhere. Like in Java, the characters are grouped into constructs called whitespace (sequences of spaces, tabs, new lines, etc.) and tokens that the Go compiler parses to process Go code. Go often uses whitespace as token separators. Except for new lines, a sequence of whitespace is treated like it was a single space character. In Go, a new line can implicitly generate a semicolon (;) statement ender so it is somewhat special. The Go lexical analyzer automatically adds a semicolon when a line end is encountered, and a semicolon is allowed after the prior token. In general, lines can be split after a comma (,) and in some brace ({...}) or parentheses ((...)) enclosed lists. While convenient, this also restricts where certain tokens must appear relative to each other. Go is thus stricter about source statement arrangement into lines than Java is. Most significant is the block-introducing open brace ({), which must be on the same line as any prefix statement. You will see lots of examples of this in this book. One generally thinks of Go programs as a stream of tokens, often arranged in a sequence of lines of code. Tokens are commonly identifiers, some of which are reserved words, delimiters, and punctuation or operators. Here is a simple Go source file (based on the common Hello World example) in a file typically called main.go in a directory typically called main: