Saturday, August 24, 2019

Go Constants

Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
Constants are treated just like regular variables except that their values cannot be modified after their definition.

Integer Literals

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals −
212         /* Legal */
215u        /* Legal */
0xFeeL      /* Legal */
078         /* Illegal: 8 is not an octal digit */
032UU       /* Illegal: cannot repeat a suffix */
Following are other examples of various type of Integer literals −
85         /* decimal */
0213       /* octal */
0x4b       /* hexadecimal */
30         /* int */
30u        /* unsigned int */
30l        /* long */
30ul       /* unsigned long */

Floating-point Literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals −
3.14159       /* Legal */
314159E-5L    /* Legal */
510E          /* Illegal: incomplete exponent */
210f          /* Illegal: no decimal or exponent */
.e55          /* Illegal: missing integer or fraction */

Escape Sequence

When certain characters are preceded by a backslash, they will have a special meaning in Go. These are known as Escape Sequence codes which are used to represent newline (\n), tab (\t), backspace, etc. Here, you have a list of some of such escape sequence codes −
Escape sequenceMeaning
\\\ character
\'' character
\"" character
\?? character
\aAlert or bell
\bBackspace
\fForm feed
\nNewline
\rCarriage return
\tHorizontal tab
\vVertical tab
\oooOctal number of one to three digits
\xhh . . .Hexadecimal number of one or more digits
The following example shows how to use \t in a program −

package main

import "fmt"

func main() {
   fmt.Printf("Hello\tWorld!")
}
When the above code is compiled and executed, it produces the following result −
Hello World!

String Literals in Go

String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"

"hello, \

dear"

"hello, " "d" "ear"

The const Keyword

You can use const prefix to declare constants with a specific type as follows −
const variable type = value;
The following example shows how to use the const keyword −

package main

import "fmt"

func main() {
   const LENGTH int = 10
   const WIDTH int = 5   
   var area int

   area = LENGTH * WIDTH
   fmt.Printf("value of area : %d", area)   
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
Note that it is a good programming practice to define constants in CAPITALS.

Go - Variables

A variable is nothing but a name given to a storage area that the programs can manipulate. Each variable in Go has a specific type, which determines the size and layout of the variable's memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Go is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types −
Sr.NoType & Description
1
byte
Typically a single octet(one byte). This is an byte type.
2
int
The most natural size of integer for the machine.
3
float32
A single-precision floating point value.
Go programming language also allows to define various other types of variables such as Enumeration, Pointer, Array, Structure, and Union, which we will discuss in subsequent chapters. In this chapter, we will focus only basic variable types.

Variable Definition in Go

A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows −
var variable_list optional_data_type;
Here, optional_data_type is a valid Go data type including byte, int, float32, complex64, boolean or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −
var  i, j, k int;
var  c, ch byte;
var  f, salary float32;
d =  42;
The statement “var i, j, k;” declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j, and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The type of variable is automatically judged by the compiler based on the value passed to it. The initializer consists of an equal sign followed by a constant expression as follows −
variable_name = value;
For example,
d = 3, f = 5;    // declaration of d and f. Here d and f are int 
For definition without an initializer: variables with static storage duration are implicitly initialized with nil (all bytes have the value 0); the initial value of all other variables is zero value of their data type.

Static Type Declaration in Go

A static type variable declaration provides assurance to the compiler that there is one variable available with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail of the variable. A variable declaration has its meaning at the time of compilation only, the compiler needs the actual variable declaration at the time of linking of the program.

Example

Try the following example, where the variable has been declared with a type and initialized inside the main function −

package main

import "fmt"

func main() {
   var x float64
   x = 20.0
   fmt.Println(x)
   fmt.Printf("x is of type %T\n", x)
}
When the above code is compiled and executed, it produces the following result −
20
x is of type float64

Dynamic Type Declaration / Type Inference in Go

A dynamic type variable declaration requires the compiler to interpret the type of the variable based on the value passed to it. The compiler does not require a variable to have type statically as a necessary requirement.

Example

Try the following example, where the variables have been declared without any type. Notice, in case of type inference, we initialized the variable y with := operator, whereas x is initialized using = operator.

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) 
}
When the above code is compiled and executed, it produces the following result −
20
42
x is of type float64
y is of type int

Mixed Variable Declaration in Go

Variables of different types can be declared in one go using type inference.

Example


package main

import "fmt"

func main() {
   var a, b, c = 3, 4, "foo"  
 
   fmt.Println(a)
   fmt.Println(b)
   fmt.Println(c)
   fmt.Printf("a is of type %T\n", a)
   fmt.Printf("b is of type %T\n", b)
   fmt.Printf("c is of type %T\n", c)
}
When the above code is compiled and executed, it produces the following result −
3
4
foo
a is of type int
b is of type int
c is of type string

The lvalues and the rvalues in Go

There are two kinds of expressions in Go −
  • lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.
  • rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side.
The following statement is valid −
x = 20.0
The following statement is not valid. It would generate compile-time error −
10 = 20

Go - Data Types

Variables can be of different types like int, float, struct, slice or it can be of the interface.
The general form for declaring a variable uses the keyword var:

Syntax:-

  1. var identifier type  
Example
  1. var a int  
  2. var b bool  
  3. var str string  
when a variable is declared with var it automatically initializes it to the zero-value defined for its type. A type defines the set of values and the set of operations that can take place on those values.
GO Simple Data Type Example
  1. package main  
  2. import "fmt"  
  3. func main() {  
  4.    var i int  
  5.    var f float64  
  6.    var b bool  
  7.    var s string  
  8.    fmt.Printf("%T %T %T %T\n",i,f,b,s) // Prints type of the variable  
  9.    fmt.Printf("%v   %v      %v  %q     \n", i, f, b, s) //prints initial value of the variable  
  10. }  
Output:
int float64 bool string
0   0           false  ""    

Go Construct and Data Types

The Go source code is stored in .go file. The name of the file consists of lowercase letters. If the file name has several parts, it should be separated by underscore "_" .
Go file has a name or an identifier which is case sensitive like C.
For example: a, ax123, i etc.
The _ identifier is special. It is called blank identifier. It may be used in variable declarations.
It is like normal identifiers but its value is discarded, so it cannot be used anymore in the code.
It may happen that the variable, type, or function has no name and even enhance flexibility so it is called anonymous.
These are the 25 keywords for Go-code:
breakdefaultfuncinterfaceselect
casedefergomapstruct
chanelsegotopackageswitch
constfallthroughIfrangetype
continueforimportreturnvar
Programs consist of keywords, constants, variables, operators, types and functions.
The following delimiters are used in constructs such as parentheses ( ), brackets [ ] and braces { }.
The following punctuation characters . , ; : and ... are used.
appendboolbytecapclosecomplexcomplex64complex128uint16
copyfalsefloat32float64imagintint8int16uint32
int32int64iotalenmakenewnilpanicuint64
printprintlnrealrecoverstringtrueuintuint8Uintptr


Go - Basic Syntax

We discussed the basic structure of a Go program in the previous chapter. Now it will be easy to understand the other basic building blocks of the Go programming language.

Tokens in Go

A Go program consists of various tokens. 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 Separator

In a Go program, the line separator key is a statement terminator. That is, individual statements don't need a special separator like “;” in C. The Go compiler internally places “;” as the statement terminator to indicate the end of one logical entity.
For example, take a look at the following statements −
fmt.Println("Hello, World!")
fmt.Println("I am in Go Programming World!")

Comments

Comments are like helping texts 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).
identifier = letter { letter | unicode_digit }.
Go does not allow punctuation characters such as @, $, and % within identifiers. Go is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in Go. Here are some examples of acceptable identifiers −
mahesh      kumar   abc   move_name   a_123
myname50   _temp    j      a23b9      retVal

Keywords

The following list shows the reserved words in Go. These reserved words may not be used as constant or variable or any other identifier names.
breakdefaultfuncinterfaceselect
casedeferGomapStruct
chanelseGotopackageSwitch
constfallthroughifrangeType
continueforimportreturnVar

Whitespace in Go

Whitespace is the term used in Go to describe blanks, tabs, newline characters, and comments. A line containing only whitespace, possibly with a comment, is known as a blank line, and a Go compiler totally ignores it.
Whitespaces separate one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement −
var age int;
There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement −
fruit = apples + oranges;   // get the total fruit
No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.

Go - Program Structure

Before we study the basic building blocks of Go programming language, let us first discuss the bare minimum structure of Go programs so that we can take it as a reference in subsequent chapters.

Hello World Example

A Go program basically consists of the following parts −
  • Package Declaration
  • Import Packages
  • Functions
  • Variables
  • Statements and 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 take a look at the various parts of the above program −
  • The first line of the program package main defines the package name in which this program should lie. It is a mandatory statement, as Go programs run in packages. The main package is the starting point to run the program. Each package has a path and name associated with it.
  • The next line import "fmt" is a preprocessor command which tells the Go compiler to include the files lying in the package fmt.
  • The next line func main() is the main function where the program execution begins.
  • The next line /*...*/ is ignored by the compiler and it is there to add comments in the program. Comments are also represented using // similar to Java or C++ comments.
  • 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 the message on the screen.
  • Notice the capital P of Println method. In Go language, a name is exported if it starts with capital letter. Exported means the function or variable/constant is accessible to the importer of the respective package.

Executing a Go Program

Let us discuss how to save the source code in a file, compile it, and finally execute the program. Please follow the steps given below −
  • Open a text editor and add the above-mentioned code.
  • Save the file as hello.go
  • Open the command prompt.
  • Go to the directory where you saved the file.
  • Type go run hello.go and press enter to run your code.
  • If there are no errors in your code, then you will see "Hello World!" printed on the screen.
$ go run hello.go
Hello, World!
Make sure the Go compiler is in your path and that you are running it in the directory containing the source file hello.go.

How to Download and install GO

Step 1) Go to https://golang.org/dl/. Download the binary for your OS.
Step 2) Double click on the installer and click Run.
Step 3) Click Next
Step 4) Select the installation folder and click Next.
Step 5) Click Finish once the installation is complete.
Step 6) Once the installation is complete you can verify it by opening the terminal and typing
go version
This will display the version of go installed

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...