Minggu, 09 Oktober 2016

Learning Golang (Part 2)

Now your first hello world Golang programs should already worked, let's see what is the meaning of each line.


package main

import "fmt"

func main() {
   /* This is my first sample program. */
   fmt.Println("Hello, World!")
}
  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 Golang Program

   In part 1, we execute Golang program using a command prompt. In this occassion I'll share how to use a plugin that will help you execute it in Notepad++.
After you install Golang installable archieve :
  1. Open Notepad++
  2. Select Plugins > Plugin Manager > Show Plugin Manager (Image 1)
  3. Search for GOnpp
  4. Install
  5. Enjoy

GOnpp assists you writing Go-programms. It has code completion and function calltips (using gocode, see below) as well as direct interaction with the go command. Currently the following actions are implemented:
gocode complete -> ALT+O || gocode calltip -> ALT+P
go fmt -> ALT+F || go test -> ALT+T || go install -> ALT+I || go run -> ALT+R
Note : If you install Golang in a custom location, you need to add GOROOT and GOBIN in system's environment variables


Highlight Golang Codes

This is for Notepad++ too, I have a custom highlight xml for golang. You can download it here. Now, to apply it :
  1. Open Notepad++
  2. Select Language > Define your language
  3. Select import > Navigate to downloaded golang.xml
  4. Save
  5. You may need to restart Notepad++
  6. Select Language > Go
  7. Enjoy


Line Seperator

   Actually I think Golang is pretty similar to C++, it has pointer, struct, no inheritance, but there're also some differences. One of them is the line separator. 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.


fmt.Println("Hello, World!")
fmt.Println("I am in Go Programming World!")
So, basically the codes above will not produce an error. It will works normally.
It is good, we don't need to waste time when there's a dumb error because of ;.
But, on the other side codes below will produces error. 
if(goal = 10)
{
    fmt.Println("Finished")
}
You have to change it to be like this 
if(goal = 10){
    fmt.Println("Finished")
}
Why? Because end of each line is matters.Well it depends on your style, but for me this is annoying hahaha...


Identifiers

A Golang identifier is a name used to identify a variable, function, or any other user-defined item. Basically, you can use any character except punctuation characters such as  @, $, and % within the identifiers. These are some acceptable identifiers :
mouse       i

_animal     source_File

Kingdom     myAddress

For details, you can access my source link below (tutorialspoint, it is really good). 

Variables

There are 2 ways to create a variables in Golang :

  • Define the data type by yourself
var list_variable_names optional_data_type /*This is the format to create variable*/
var   c, ch int
var  f, salary float32
c = 42;
  • Let Golang decide the data type (only for primitive data types)
package main

import "fmt"

func main() {
   var x float64 = 20.0

   y := 42 
   fmt.Println(x)
   fmt.Println(y)
   fmt.Printf("x is of type %T\n", x)
   fmt.Printf("y is of type %T\n", y) 
}

And, the result is
20
42
x is of type float64
y is of type int

You can also declare a multiple type variables in 1 line

var number1, number2, text = 10, 20, "multiple type variables"

Source :
- https://www.tutorialspoint.com/go/go_program_structure.htm






Learning Golang (Part 1)

Overview
Go (often referred to as golang) is a Free and open source programming language created at Google in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is a compiled, statically typed language in the tradition of Algol and C, with garbage collection, limited structural typing, memory safety features and CSP-style concurrent programming features added.

The language was announced in November 2009; it is used in some of Google's production systems, as well as by other firms. Two major implementations exist: Google's Go compiler, "gc", is developed as open source software and targets various platforms including Linux, OS X, Windows, various BSD and Unix versions, and since 2015 also mobile devices, including smartphones. A second compiler, gccgo, is a GCC frontend. The "gc" toolchain is self-hosting since version 1.5.

Go originated as an experiment by Google engineers Robert Griesemer, Rob Pike, and Ken Thompson to design a new programming language that would resolve common criticisms of other languages while maintaining their positive characteristics. The new language was to:

  1. be statically typed, scalable to large systems (as Java and C++); 
  2. be productive and readable, without too many mandatory keywords and repetition ("light on the page" like dynamic languages); 
  3. not require tooling, but support it well
  4. support networking and multiprocessing.

In later interviews, all three of the language designers cited their shared dislike of C++'s complexity as a primary motivation for designing a new language. Go 1.7 added "one tiny language change" and one port to macOS 10.12 Sierra plus some experimental ports, e.g. for Linux on z Systems (linux/s390x). Some library changes apply, and e.g. Unicode 9.0 is now supported.

Design Principles of Golang

  1. 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) 
  2. Compilation time is fast.
  3. InBuilt concurrency support: light-weight processes (via goroutines), channels, select statement.
  4. Conciseness, Simplicity, and Safety
  5. Support for Interfaces and Type embedding.
  6. Production of statically linked native binaries without external dependencies. 
Features excluded intentionally 

  1. To keep language simple and concise, following features commonly available in similar languages are ommitted
  2. No support for type inheritance
  3. No support for method or operator overloading
  4. No support for circular dependencies among packages
  5. No support for pointer arithmetic
  6. No support for assertions
  7. No support for generic programming 
Getting Started 
The source files for Go programs are named with the extension ".go". First of all we need a Golang installable archieve to start it. You can download it here

    Install on Linux, Mac OS X, and FreeBSD tarballs 
      Download the archive and extract it into /usr/local, creating a Go tree in /usr/local/go. For example:
tar -C /usr/local -xzf go$VERSION.$OS-$ARCH.tar.gz
Choose the archive file appropriate for your installation. For instance, if you are installing Go version 1.2.1 for 64-bit x86 on Linux, the archive you want is called go1.2.1.linux-amd64.tar.gz. (Typically these commands must be run as root or through sudo.) Add /usr/local/go/bin to the PATH environment variable. You can do this by adding this line to your /etc/profile (for a system-wide installation) or $HOME/.profile:
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.

   Test it
    Create a go file, save it as hello.go in D:\>Go_Workspace.
Filename : hello.go
package main

import "fmt"

func main() {
   fmt.Println("Hello world!")
}
  Now run the test.go to see the result:
D:\Go_Workspace>go run hello.go
Verify the Output
Hello world!
That's it for now, next we will learn the basics of Golang


Source :
- https://en.wikipedia.org/wiki/Go_(programming_language) 
- https://www.tutorialspoint.com/go/go_overview.htm 
- https://golang.org/doc/install