Rabu, 20 Juni 2018

Sponsored Links

The Go Programming Language - Part 01 - YouTube
src: i.ytimg.com

Go (often referred to as Goal ) is a programming language created on Google in 2009 by Robert Griesemer, Rob Pike, and Ken Thompson. Go is a statically compiled language typed in the C tradition, with memory security, garbage collection, structural typing, and CSP-style concurrent programming features added. Compilers and other tools originally developed by Google are all free and open source.


Video Go (programming language)



History

This language was announced in November 2009. Version 1.0 was released in March 2012. It is used in some Google production systems, as well as by many other companies and open source projects.

Two major implementations exist:

  • Toolchain Go Google, which targets platforms including Linux, BSD, OS X, Plan 9, Windows, and (since 2015) mobile devices. The Go main compiler has been hosting itself since version 1.5.
  • The second compiler, gccgo, is the GCC frontend.

Go originated as an experiment by Google engineers Robert Griesemer, Rob Pike, and Ken Thompson to devise a new programming language that would solve general criticism of other languages ​​while maintaining their positive characteristics. The developers envision a new language as:

  • Typed statically and scalable to large systems (like Java or C)
  • Productive and easy to read, without excessive boilers (like dynamic languages ​​like Ruby or Python)
  • Does not require an integrated development environment, but supports it well
  • Support for network and multiprocessing

In subsequent interviews, the three language designers mentioned their dislike for C as the main motivation for designing a new language.

Maps Go (programming language)



Design language

Go is recognized in tradition C, but makes many changes to improve brevity, simplicity, and security. Go consists of:

  • Syntax and environment adopt more general patterns in dynamic languages:
    • Optional shortcut variable declaration and initialization via type inference ( x: = 0 instead of int x = 0; or var x = 0; ).
    • Compile time is fast.
    • Remote package management ( go get ) and online package documentation.
  • A specific approach to a particular problem:
    • Built-in primitive concurrency: lightweight process (goroutines), channels, and select statements.
    • The interface system replaces the virtual inheritance, and the embed type is not a non-virtual inheritance.
    • Toolchain which, by default, generates native binaries that are connected statically without external dependencies.
  • The desire to preserve language specifications is simple enough to hold on to the programmer's head, in part by eliminating common features in the same language.

Syntax

The Go syntax includes a change from C that aims to keep the code concise and easy to read. A combined declaration/initialization operator was introduced that allowed the programmer to write i: 3 or s: = "Hello, world!" , without specifying the variable type. This contrasts with C int i = 3; and const char * s = "Hello, world!"; . The semicolon still terminates the statement, but is implicit when the end of the line occurs. The function can return multiple values, and returning the pair of result, err is the conventional way a function indicates an error to the caller in Go. Go adds a literal syntax to initialize struct parameters by name, and to initialize maps and slices. As an alternative to the three circles of the C statement for , the Go expression allows for a concise repetition of layouts, slices, strings, maps, and channels.

Type

Go has several default types, including numeric ones ( bytes , int64 , float32 , etc.), Boolean, and string characters ( string ). String can not be changed; operators and built-in keywords (not functions) provide coding, benchmarking, and UTF-8 encoding and decoding. Recording types can be defined with the keyword struct .

For each type of T and any non-negative integers are constant n , there is a line type denoted n ] T ; arrays of different lengths thus of different types. Dynamic arrays are available as "slices", denoted [] T for some types T . It has a length and capacity determines when new memory needs to be allocated to expand the array. Some slices can share the underlying memory.

Pointer is available for all types, and pointer-to-type T is denoted * T . Address retrieval and indirection using & amp; and * as in C, or occurs implicitly through method call or access attribute syntax. No pointer arithmetic, except through special unsafe.Pointer types in standard libraries.

For a pair of K types, V , type map [ K ] V is the type of hash table type mapping- K key for typing- V value. The hash table is built into the language, with special syntax and built-in functions. chan T is a channel that allows the sending of T type values ​​between concurrent Go processes.

In addition to support for the interface, the Go type system is nominal: the type keyword can be used to define a new named type , which is different from other named types that have the same layout ( in the case of struct , the same member in the same order). Multiple conversions between types (e.g., Among different integers types) are predefined and adding new types may specify additional conversions, but conversions between named types must always be explicitly called. For example, the keyword type can be used to specify an IPv4 address type, based on a 32-bit unsigned integer.

By definition of this type, ipv4addr (x) translates the uint32 x value as the IP address. Simply specifying x to type variable ipv4addr is a type error.

Constant expressions can be typed or "not imitated"; they are assigned a type when assigned to a typed variable if the value they represent passes through the compile time check.

The function type is indicated by the keyword func ; they take zero or more parameters and return zero or more values, all of which are typed. Parameters and return values ​​specify the type of function; thus, func (string, int32) (int, error) is a type of function that takes string and integer is marked 32-bit, and returns an unmarked integer (of default width) and the value of the built-in interface type error .

Each named type has a set of methods associated with it. The example of the above IP address can be extended by a method to check if the value is a known standard.

Due to the nominal typing, the definition of this method adds a method to ipv4addr , but not to uint32 . While the method has a special definition and call syntax, there are no different types of methods.

Interface system

Go provides two features that replace class inheritance.

The first is embedding , which can be seen as a form of automatic composition or delegation.

The second is the interface , which provides runtime polymorphism. The interface is a type class and provides a finite structural type of typing in the nominal type system of Go. An object that is an interface type is also another type, the same as the C object simultaneously from the base and the derived class. Go interface is designed after the protocol of the Smalltalk programming language. Some sources use the term duck typing when describing the Go interface. Although the term typing ducks is not exactly defined and therefore not wrong, it usually means that the type of conformity is not checked statically. Since conformity with the Go interface is checked statically by the Go compiler (except when performing type statements), the Go writer prefers to use the term structural typing .

The definition of the interface type lists the required methods by name and type. Any object of type T whose function corresponds to all the required methods of interface type I is a type I object as well. T type definitions do not need (and can not) identify type I. For example, if Shape , Square and Circle is defined as:

Both Square and Circle are implicitly and can be set to the Shape -typed variable. In formal language, the Go interface system provides structural mastery rather than nominal typing. The interface can embed another interface with the effect of creating a composite interface that is satisfied by the type that implements the embedded interface and any added methods the newly added interface has.

The Go standard library uses the interface to deliver announcements in multiple places, including an input/output system based on the Readers and Writer concepts.

In addition to calling methods through the interface, Go lets convert interface values ​​to another type with a time-run type check. The build language for doing so is the statement type , which checks against a single potential type, and switch type , which checks against some types.

The interface blank interface {} is an important base case because it can refer to any concrete type item . This is similar to the Object class in Java or C # and is filled by any type, including built-in types like int . Code that uses an empty interface can not simply call a method (or built-in operator) on the referenced object, but it can save the interface {} value, try to convert it into a more useful type via statement type or type switch, or check with Go package reflect . Since interface {} can refer to any value, it is a limited way to avoid static typing restrictions, such as void * in C but with additional run-time type checks.

The interface value is implemented using the pointer to the data and the second pointer to the run-time type information. As some other types are implemented using pointers in Go, the interface value is nil if it is not initialized.

Package system

In the Go packet system, each packet has a path (for example, "compress/bzip2" or "golang.org/x/net/html" ) and name (e.g., bzip2 or html ). References to other packet definitions must be always starting with another package name, and only the capitalization names of other accessible packages: io.Reader are public but bzip2.reader is not. The go get command can retrieve packets stored in a remote repository like GitHub, and developers are encouraged to develop packages within the base path associated with the source repository (such as github.com/user_name/package_name) to reduce the chance of a collision names with future additions to standard libraries or other external libraries.

The proposal exists to introduce the right package management solution for Go similar to the Rust cargo system or the Npm npm system.

Concurrency: goroutines and channels

Go Language has built-in facilities, as well as library support, for writing concurrent programs. Concurrency refers not only to CPU parallelism, but also to asynchrony: allowing slow operations like database or network-reads to run when a program does another job, as is common in event-based servers.

Concrete concurrency primary is goroutine , a kind of light process. The function call begins with the go keyword starting the function in the new goroutine. The language specification does not specify how goroutine should be implemented, but the current implementation multiplex, a process strokes Go to a smaller set of operating systems, similar to scheduling done in Erlang.

While the standard library package featuring most classic concurrency control structures (mutex keys, etc.) is available, idiomatic concurrent programs prefer channels , which provide messaging between goroutines. Optional buffers store messages in a FIFO sequence and allow sending goroutines to continue before their messages are received.

The channel is typed, so the chan T type channel can only be used to transfer messages of type T . Special syntax is used to operate it; & lt; -ch is the expression that causes the executing gorunter to block until the value goes through the ch channel, while ch & lt; - x sends a value of x (may block until another goroutine receives its value). Default switch -like select statements can be used to implement non-blocking communications on multiple channels; see below for an example. Go has a memory model that explains how goroutine should use channels or other operations to share data securely.

There is a channel set. Remove from the language model-style actor simultaneously like Erlang, where the message is directed to the actor (according to the goroutines). Actor styles can be simulated on Go by maintaining a one-to-one correspondence between goroutines and channels, but the language allows multiple goroutines to share a single channel or goroutine to transmit and receive across multiple channels.

From this tool one can construct concurrent constructs such as worker pools, pipelines (where, say, files are decompressed and decomposed when downloaded), background calls with timeout, parallel call "ignition" to a set of services, and more. Channels have also found further use of the idea of ​​regular interprocess communication, such as serving as a concrete safe list of recycled buffers, applying coroutines (which help inspire the name goroutine ), and applying iterators.

The related Go Concurrency structural conventions (channels and alternative channel inputs) are from Tony Hoare communicating the sequential process model. Unlike previous concurrent programming languages ​​like Occam or Limbo (the language in which Go co-designer Rob Pike works), Go does not provide concrete ideas that are safe or verifiable. While the preferred process communication model on Go, this is not the only one: all the goroutines in the program share one address space. This means that objects and pointers that can be changed can be shared between goroutines; see Ã,§Ã, Lack of security condition of the race, below.

Matches for parallel programming

Although the Go concurrency feature is not aimed primarily at parallel processing, this feature can be used to program multiple shared memory processor machines. Various studies have been conducted into the effectiveness of this approach. One of these studies compares the size (in line of code) and program speed written by experienced programmers who are not familiar with the language and corrections for the program by a Go expert (from the Google development team), do the same for Chapel, Cilk and Intel TBB. The study found that non-experts tend to write split-and-conquer algorithms with one go statement per recursion, while the write-expert distributes work-synchronization programs using one goroutine per processor. Expert programs are usually faster, but also longer.

Lack of race condition security

There is no limit on how goroutines access shared data, making race conditions possible. Specifically, unless a program explicitly synchronizes through channels or other means, writing from one goroutine may be partial, entirely, or not at all visible to the other, often unsecured about writing orders. In addition, internal data structures such as interface values, slice headers, hash tables, and header strings are not immune to racing conditions, so security types and memory can be violated in multithreaded programs that change the shared instance of those types without sync. An internal Google document states that one of the design goals agreed upon for Go is that the three language designers must agree that certain features may be included.

Instead of language support, secure concurrent programming relies on conventions; for example, Chisnall recommends an idiom called "alias xor may change", meaning that it passes a mutable value (or pointer) through the signal channel transfer of ownership over the value to the receiver.

Negligence

Going deliberately eliminates certain features common in other languages, including (implementation) inheritance, generic programming, statements, pointer arithmetic, and implicit type conversions.

From these language features, the author Go discloses openness to generic programming, explicitly defies pointer statements and arithmetic, while maintaining the option to eliminate inherited types as giving more useful language, encouraging otherwise use of interfaces to achieve dynamic delivery and composition to use return code. Compositions and delegates are in fact mostly automated by embedding struct ; according to Schmager researchers et al. , this feature "has many legacy flaws: it affects the public interface of the object, it is not fine (ie, no level control method over embedding), embedded object method can not be hidden, and it's static", make it " "whether the programmer will not overuse it to the point that programmers in other languages ​​are considered to be using too much inheritance.

Regarding generic programming, some of the built-in functions are in fact generic types, but these are treated as special cases; Rob Pike calls this a language weakness that can someday be changed. The Google team that designed the language built at least one compiler for experimental Go dial by generic, but did not release it.

After initially omitting exceptions, mechanisms like panic / recover are finally added to the language, suggested by Go authors using an irreversible error that should stop the entire program or server request , or as a shortcut to spread stacking errors in packets (but not across packet boundaries; there, returning errors is a standard API).

Criticism

Critics claim that:

  • lack of generic compile time leads to code duplication, metaprogramming can not be checked statically and standard libraries can not offer generic algorithms
  • lack of exceptions makes some error handling patterns to be difficult, such as treating some failed statements as blocking
  • lack of language extension capabilities (through, for example, operator overloading) makes certain tasks more verbose
  • lack of a Hindley-Milner type system that suppresses security and/or hampering expressions
  • pause and garbage collection overhead ( GC ) limit the use of Go in system programming compared to languages ​​with manual memory management.

The language designers argue that this trade-off is important for Go's success, and explains some specific decisions at length, although they express openness to add some form of generic programming in the future, and to pragmatic improvements in areas such as standardizing ways to implement making code.

The GC has been fixed to the sub-millisecond pause in the newer version. However, developers recognize that the GC algorithm is not difficult in real-time.

doc/gopher/ - The Go Programming Language
src: golang.org


Conventions and code styles

The authors go to great lengths to shape the style and design of the Go program:

  • Indents, spaces, and other surface level details of the code are automatically standardized by the gofmt tool. golint performs additional style checks automatically.
  • Tools and libraries distributed with Go suggest standard approaches for things like API documentation ( godoc ), testing ( go test ), development ( go build ), package management ( go get ), and so on.
  • Go enforces rules that are recommendations in other languages, such as banning cyclical dependencies, unused variables or imports, and implicit type conversions.
  • The negligence of certain features (eg functional programming shortcuts like map and Java style try / finally blocks) tend to encourage certain explicit, concrete, and imperative programming styles.
  • On the first day Go's team publishes the Go idiom collection, and then also collects code review comments, talks, official blog posts to teach Go styles and coding philosophy.

go programming language passing data on the web - YouTube
src: i.ytimg.com


Language tools

Go includes the same debug type, test, and code-checking tool as many language distributions. Go Distributions include, among other tools,

  • go build , which builds the Go bin using only the information in the source file itself, no separate makefile
  • go test , for unit testing and microbenchmarks
  • go fmt , to format the code
  • get , to retrieve and install the remote package
  • go vet , a static analyzer looks for potential errors in the
  • code
  • run , shortcuts to create and execute code
  • godoc , to display documentation or serve via HTTP
  • gorename , to change the variable name, function, and so on in a secure way
  • go generate , the standard way to run code generator

It also includes profile and debugging support, runtime instrumentation (for, for example, tracing garbage collection gap), and race condition tester.

There are third-party ecosystem tools that add standard distributions, such as gocode , which allows autocomplete of code in many text editors, goimports (by Go team members), which automatically add/remove the import package as needed, errcheck , which detects code that may have accidentally ignored errors, and more. The plugin exists to add language support to some widely used text editor. In addition, some IDEs are available. For example, LiteIDE, which is labeled as "an open source, Open Source, simple cross-platform", and GoLand, which claims to be "capable and ergonomic."

Why Google Go Should be the Next Programming Language you Learn
src: freelancermap.s3.amazonaws.com


Example

Hello world

Here is the Hello world program on Go:

Sample concurrency

The following simple program shows the Go concurrency feature to implement asynchronous programs. It launches two "goroutines" (light threads): one waits for the user to type some text, while the other implements a deadline. The select statement waits for one of these goroutines to send a message to the main routine, and acts on the first message to come (example adapted from David Chisnall's book).

Getting Started with The Go Programming Language ( golang ) at ...
src: i.ytimg.com


Project using Go

Some important open-source applications on Go include:

  • "Lightning Network", bitcoin network that enables transactions and Bitcoin scalability fast.
  • Decred, a cryptocurrency with on-chain governance integrated into its blockchain.
  • Caddy, an open source HTTP/2 web server with automatic HTTPS capability.
  • CockroachDB, an open, persistent, and very consistent SQL database.
  • Docker, a set of tools for deploying Linux containers
  • Hugo, static site generator
  • InfluxDB, a special open source database for handling time series data with high availability and high performance requirements.
  • Juju, a service orchestration tool by Canonical, the Ubuntu Linux package maker
  • Kubernetes container management system
  • OpenShift, cloud computing platform as a service by Red Hat
  • Snappy, the package manager for Ubuntu Touch developed by Canonical.
  • Syncthing, an open source client/server sync application file
  • Terraform, an open source, multi-operating cloud infrastructure infrastructure tool from HashiCorp.
  • The Interconnan File System, the addressable addressable peer-to-peer hypermedia protocol.

Companies and other well-known sites that use Go (generally along with other languages, not exclusive) include:

  • Cacoo, to render them from the user dashboard page and microservice using Go and gRPC.
  • Chango, a programmable advertising company using Go in its real-time bidding system.
  • Cloud Foundry, the platform as a service
  • CloudFlare, for their Railgun delta-coding proxy, their distributed DNS service, as well as tools for cryptography, recording, streaming processing, and accessing SPDY sites.
  • CoreOS, a Linux-based operating system that uses Docker containers and rkt containers.
  • Couchbase, Query and Indexing Service in Couchbase Server
  • Dropbox, move some of their important components from Python to Go
  • Google, for many projects, especially including download servers dl.google.com
  • Heroku, for Doozer, key service
  • Hyperledger Fabric, open source, ledger project distributed by the company
  • MercadoLibre, for some public APIs.
  • MongoDB, a tool for managing MongoDB instances
  • Netflix, for two parts of their server architecture
  • Novartis, for the internal inventory system
  • Nutanix, for various micro services in its Enterprise Cloud OS.
  • Plug.dj, an interactive online social music streaming website.
  • SendGrid, Boulder, mail delivery and transactional management service based in Colorado.
  • SoundCloud, for "dozens of systems"
  • Splice, for their entire backend (API and parser) online music collaboration platform.
  • ThoughtWorks, some tools and apps for continuous delivery and instant messaging (CoyIM).
  • Twitch.tv, for their IRC based chat system (migrated from Python).
  • Uber, to handle high-volume geofence-based queries.
  • Zerodha, for a peek in realtime and streaming market data

Programming: Go â€
src: s3.amazonaws.com


Reception

The interface system, and deliberate deliberate inheritance, is praised by Michele Simionato, who likens the characteristics of this language to the ML standard, calling it "shameful that no popular language follows [this] particular route in the design room".

Dave Astels di Engine Yard menulis:

Go is very easy to dive. There is a minimal amount of basic language concepts and their syntax is clean and designed to be clear and unambiguous. Go is still experimental and still slightly crude on the edges.

Ars Technica interviewed Rob Pike, one of the authors of Go, and asked why new languages ​​were needed. He replied that:

It's not enough to just add features to an existing programming language, because sometimes you can get more in the long run by taking a few things. They want to start over and rethink everything.... [But they do not want to] deviate too much from what the developers already know because they want to avoid alienating the target audience Go.

Go was named Programming Language of the Year by the TIOBE Programming Community Index in its first year, 2009, due to a 12 month popularity increase larger (in just 2 months, after its introduction in November) than any other language of the year, and reached 13th place in January 2010, exceeding existing languages ​​like Pascal. In June 2015, its ranking fell below 50 in the index, placing it lower than COBOL and Fortran. But by January 2017, its ranking has jumped to 13 again, showing significant growth in popularity and adoption. Go was awarded the 2016 TIOBE programming language.

About Go, Bruce Eckel has stated:

The complexity of C (even more complexity has been added in the new C), and the resulting impact on productivity, is no longer justified. All the circles that C programmers must pass through to use C-compatible languages ​​do not make any sense - they are just a waste of time and effort. Go makes more sense for a class of problems that was originally intended to solve C.

Language evaluation in 2011 and its implementation of gc compared to C (GCC), Java and Scala by a Google engineer found that:

Go offers interesting language features, which also allows for concise and standard notation. The compiler for this language is still immature, reflecting both performance and binary sizes.

Evaluation received a rebuttal from the Go development team. Ian Lance Taylor, who has improved the Go code for Hundt papers, has not yet known the intention to publish his work, and said that his version "was never meant to be an idiomatic or efficient Go instance"; Russ Cox then optimizes the Go code, as well as the C code, and gets the Go code running slightly faster than C and more than one order of magnitude faster than the "optimized" code on the paper.

Go Programming Language - YouTube
src: i.ytimg.com


Naming dispute

On November 10, 2009, the day of the general language launch, Francis McCabe, the developer of Go! programming language (note an exclamation point), ask for a change in the Google language name to prevent confusion with the language, which has spent 10 years developing. McCabe voiced concern that "the 'big guy' would end up with rocks about" him, and these concerns resonated with over 120 developers who commented on the official Google official thread saying they should change the name, with some even saying the issue was at odds with Google tagline: Do not be evil.

On October 12, 2010, the issue was closed by developer Google Russ Cox (@rsc) with a special status "Malang" with the following comments:

"There are a lot of computing products and services named Go.In the 11 months since it was released, there's a bit of confusion in both languages."


Making concurrent HTTP requests in Go programming language
src: cdn-images-1.medium.com


See also

  • Comparison of programming languages ​​
  • Dart, another programming language developed at Google
  • UFC, how to have "open method" in other languages ​​

Go Programming Language - YouTube
src: i.ytimg.com


Note


The Go Programming Language Blog
src: blog.golang.org


References


3. Go Programming Language : Syntax, Variables, Data Types ...
src: i.ytimg.com


External links

  • Official website

Source of the article : Wikipedia

Comments
0 Comments