Go Quick Guide
Total Page:16
File Type:pdf, Size:1020Kb
GGOO -- QQUUIICCKK GGUUIIDDEE http://www.tutorialspoint.com/go/go_quick_guide.htm Copyright © tutorialspoint.com GGOO -- OOVVEERRVVIIEEWW Go is a general-purpose language designed with systems programming in mind.It was initially developed at Google in year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is strongly and statically typed, provides inbuilt support for garbage collection and supports concurrent programming. Programs are constructed using packages, for efficient management of dependencies. Go programming implementations use a traditional compile and link model to generate executable binaries. The Go programming language was announced in November 2009 and is used in some of the Google's production systems Design Principles Support for environment adopting patterns similar to dynamic languages. For example type inference (x := 0 is valid declaration of a variable x of type int) Compilation time is fast. InBuilt concurrency support: light-weight processes (via goroutines), channels, select statement. Conciseness, Simplicity, and Safety Support for Interfaces and Type embedding. Production of statically linked native binaries without external dependencies. Features excluded intentionally To keep language simple and concise, following features commonly available in similar languages are ommitted. No support for type inheritance No support for method or operator overloading No support for circular dependencies among packages No support for pointer arithmetic No support for assertions No support for generic programming Go Programs A Go program can vary from 3 lines to millions of lines and it should be written into one or more text files with extension ".go"; for example, hello.go. You can use "vi", "vim" or any other text editor to write your Go program into a file. This tutorial assumes that you know how to edit a text file and how to write source code inside a program file. GGOO -- EENNVVIIRROONNMMEENNTT SSEETTUUPP Try it Option Online You really do not need to set up your own environment to start learning Go programming language. Reason is very simple, we already have set up Go Programming environment online, so that you can compile and execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online. Try following example using Try it option available at the top right corner of the below sample code box: package main import "fmt" func main() { fmt.Println("Hello, World!") } For most of the examples given in this tutorial, you will find Try it option, so just make use of it and enjoy your learning. Local Environment Setup If you are still willing to set up your environment for Go programming language, you need the following two softwares available on your computer, (a) Text Editor and (b) The Go Compiler. Text Editor This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your editor are called source files and contain program source code. The source files for Go programs are typically named with the extension ".go". Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it. The Go Compiler The source code written in source file is the human readable source for your program. It needs to be "compiled", to turn into machine language so that your CPU can actually execute the program as per instructions given. This Go programming language compiler will be used to compile your source code into final executable program. I assume you have basic knowledge about a programming language compiler. Go distribution comes as a binary installable for FreeBSD (release 8 and above), Linux, Mac OS X (Snow Leopard and above), and Windows operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures. Following section guides you on how to install Go binary distribution on various OS. Download Go archive Download latest version of Go installable archive file from Go Downloads. At the time of writing this tutorial, I downloaded go1.4.windows-amd64.msi and copied it into C:\>go folder. OS Archive name Windows go1.4.windows-amd64.msi Linux go1.4.linux-amd64.tar.gz Mac go1.4.darwin-amd64-osx10.8.pkg FreeBSD go1.4.freebsd-amd64.tar.gz Installation on UNIX/Linux/Mac OS X, and FreeBSD Extract the download archive into /usr/local, creating a Go tree in /usr/local/go. For example: tar -C /usr/local -xzf go1.4.linux-amd64.tar.gz Add /usr/local/go/bin to the PATH environment variable. OS Output Linux export PATH=$PATH:/usr/local/go/bin Mac export PATH=$PATH:/usr/local/go/bin FreeBSD export PATH=$PATH:/usr/local/go/bin Installation on Windows Use the MSI file and follow the prompts to install the Go tools. By default, the installer uses the Go distribution in c:\Go. The installer should set the c:\Go\bin directory in window's PATH environment variable. Restart any open command prompts for the change to take effect. Verify installation Create a go file named test.go in C:\>Go_WorkSpace. File: test.go package main import "fmt" func main() { fmt.Println("Hello, World!") } Now run the test.go to see the result: C:\Go_WorkSpace>go run test.go Verify the Output Hello, World! GGOO -- PPRROOGGRRAAMM SSTTRRUUCCTTUURREE Before we study basic building blocks of the Go programming language, let us look a bare minimum Go program structure so that we can take it as a reference in upcoming chapters. Go Hello World Example A Go program basically consists of the following parts: Package Declaration Import Packages Functions Variables Statements & Expressions Comments Let us look at a simple code that would print the words "Hello World": package main import "fmt" func main() { /* This is my first sample program. */ fmt.Println("Hello, World!") } Let us look various parts of the above program: 1. The first line of the program package main defines the package name in which this program should lie. It is a must statement as Go programs runs in packages. main package is the starting point to run the program. Each package has a path and name associated with it. 2. The next lineimport "fmt" is a preprocessor command which tell the Go compiler to include files lying in package fmt. 3. The next line func main() is the main function where program execution begins. 4. The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program. Comments are also represented using // similar to Java or C++ comments. 5. The next line fmt.Println(...) is another function available in Go which causes the message "Hello, World!" to be displayed on the screen. Here fmt package has exported Println method which is used to display message on the screen. 6. Notice the capital P of Println method. In Go language, a name is exported if it starts with capital letter. Exported means that a function or variable/constant is accessible to importer of the respective package. Execute Go Program: Lets look at how to save the source code in a file, and how to compile and run it. Following are the simple steps: 1. Open a text editor and add the above-mentioned code. 2. Save the file as hello.go 3. Open a command prompt and go to the directory where you saved the file. 4. Type go run hello.go and press enter to run your code. 5. If there are no errors in your code then you will be able to see "Hello World" printed on the screen. $ go run hello.go Hello, World! Make sure that go compiler is in your path and that you are running it in the directory containing source file hello.go. GGOO -- BBAASSIICC SSYYNNTTAAXX You have seen a basic structure of Go program, so it will be easy to understand other basic building blocks of the Go programming language. Tokens in Go A Go program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Go statement consists of six tokens: fmt.Println("Hello, World!") The individual tokens are: fmt . Println ( "Hello, World!" ) Line Seperator In Go program, the line seperator key is a statement terminator. That is, each individual statement don't need a special seperator like ; in C. Go compiler internally places ; as statement terminator to indicate the end of one logical entity. For example, following are two different statements: fmt.Println("Hello, World!") fmt.Println("I am in Go Programming World!") Comments Comments are like helping text in your Go program and they are ignored by the compiler. They start with /* and terminates with the characters */ as shown below: /* my first program in Go */ You cannot have comments within comments and they do not occur within a string or character literals. Identifiers A Go identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).