Go - Overview
Go is a modern, generic-purpose, open-source programming language that was officially announced at the end of 2009. Go began as an internal Google project.
The language was designed by and for people who write, read, debug, and maintain large software systems. It's a statically-typed, compiled language with built-in concurrency and garbage collection.
Data types
Go supports many elementary data types, including int, bool, int32, and float64. One of the most obvious points where the language specification diverges from the familiar C/Java syntax is where, in the declaration syntax, the declared name appears before the type.?
For example
var count int
//It declares a count variable of the integer type (int).
One unique data type in Go is the error type. It's used to store errors, and there is?a helpful package called errors for working with the variables of this type:
err := errors.New("Some Error")
if err != nil {
????fmt.Print(err)
})
Go also supports compound data structures, such as string, map, array, and slice natively. The language runtime handles the details of memory management and provides the programmer with native types to work with.
var a[10]int // an array of type [10]int
Functions
As in the C/C++ world, there are code blocks called functions. They are defined by the func keyword. They have a name, some parameters, the main body of code, and optionally a list of results. The following code block defines a function to calculate the area of a circle:
func area(radius int) float64 {
var pi float64 = 3.14
return pi*radius*radius
}
It accepts a single variable, radius, of the int type, and returns a single float64 value, Within the function, a variable called pi of the float64 type is declared.
Functions in Go can return multiple values, A common case is to return the function result and an error value as a pair, as seen in the following example:
? ? ? ? func GetX() (x X, err error)
Structures
Go has concepts of structures and methods, although arrays, slices, and maps are all very useful, they cannot group and hold multiple values in the same place.?When you need to group various types of variables?and create a new handy type, you can?use a structure.?
The various elements of a structure are called the fields of the structure or just fields, A struct is?analogous to a class and encapsulates data and related operations.
For example, consider the following snippet:
type Circle struct {
Radius int
color String
}
It defines a Circle structure with two members and fields.
A method is a function with a special parameter (called a receiver), which can be passed to the function using the standard dot notation. This receiver is analogous to the self or this keyword in other languages, methods declaration syntax places the receiver in parentheses before the function name.
Here is the preceding Area function declared as a method:
func (c Circle) Area() float64 {
??? var pi float64 = 3.14
????return pi*c.radius*c.radius
}
Receivers can either be pointers (reference) or non-pointers (value). Pointer references are useful in the same way as normal pass-by-reference variables, should you want to modify struct, or if the size of a struct is large, and so on.
领英推荐
Flow control
Go has the if statement, but does not mandate parentheses for conditions. Consider the following example:
if val > 100 {
? ?fmt.Println("val is greater than 100")
} else {
? fmt.Println("val is less than or equal to 100")
}
To define loops, there is only one iteration keyword, for. There are no while or do...while keywords that we see in other languages, such as C or Java. This is in line with the Golang design principles of minimalism and simplicity—whatever we can do with a while loop, the same can be achieved with a for loop, The syntax is as follows:
func naiveSum(n Int) (int){
sum := 0;
? for i:=0; i < n ; i++ {
????? sum += index
???}
???return sum
}
As you can see, again, there are no parentheses around the loop conditions
Packaging
In Go, code is binned into packages. These packages provide a namespace for code. Every Go source file starts with a package clause, like this:
package example
Packages are rarely in isolation; they have dependencies. If code in one package wants to use something from a different package, then the dependency needs to be called out explicitly, the dependent packages can be other packages from the same project, a Golang standard package, or from a third-party package on GitHub,
after the package clause, each source file may have one or more import statements, comprising the import keyword and the package identifier:
import "encoding/json"
One important design decision in Go, dependency-wise, is that the language specification requires unused dependencies to be declared as a compile-time error (not a warning, like most other build systems).
If the source file imports a package it doesn't use, the program will not compile.
This was done to speed up build times by making the compiler work on only those packages that are needed.?For programmers, it also means that code tends to be cleaner, with fewer unused imports piling up.?
Go takes an unusual approach to defining the visibility of identifiers (functions/variables) inside a package. Unlike private and public keywords, in Go, the name itself carries the visibility definition, the case of the initial letter of the identifier determines the visibility. If the initial character is an uppercase letter, then the identifier is public and is exported out of the package. Such identifiers can be used outside of the package. Consider the following snippet:
package circle
func AreaOf(c Circle) float64 {}
func colorOf(c Circle) string {}
In the code block, the AreaOf function is exported and visible outside of the circles package, but colorOf is visible only within the package.
The standard Go library offers many packages that simplify the work of the developer. Additionally, the functions found in the standard Go library are tested and debugged in advance by the people who develop Go, which means that most of the time, they come without bugs.
Garbage collection
Garbage collection is the process of freeing up memory space that is not being used. In other words, the garbage collector sees which objects are out of scope and cannot be referenced anymore, and frees the memory space they consume. This process happens in a concurrent way while a Go program is running and not before or after the execution of the program.
Go supports garbage collection, so you do not have to deal with memory allocation and deallocation.
Object-oriented programming
Go does not have direct support for object-oriented programming, which can be a problem for programmers who are used to writing code in an object-oriented manner. Nevertheless, you can use composition in Go to mimic inheritance.
The Go way of object orientation is composition over inheritance. For polymorphic behavior, Go uses interfaces