Saturday 28 August 2021

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.

Example

This example shows some of the different data types in Go:

package main
import ("fmt")

func main() {
  var a bool = true     // Boolean
  var b int = 5         // Integer
  var c float32 = 3.14  // Floating point number
  var d string = "Hi!"  // String

  fmt.Println("Boolean: ", a)
  fmt.Println("Integer: ", b)
  fmt.Println("Float:   ", c)
  fmt.Println("String:  ", d)
}

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


No comments:

Post a Comment