jekyll-theme-chirpy
Version:
A minimal, responsive, and powerful Jekyll theme for presenting professional writing.
472 lines (315 loc) • 9.16 kB
Markdown
---
title: Data types & Variable declaration
author: mrtishca
date: 2020-11-11 12:00:00 +0600
categories: [Programing, Tutorial]
tags: [Golang]
render_with_liquid: false
image:
path: /posts/golang-install.jpg
width: 1000 # in pixels
height: 400 # in pixels
alt: GoLang Install
---
## Variable declaration
### Single declaration & Initialization
In Golang like in javascript to declare a variable, is necessary use "var" and follow the next variable declaration structure.
**Declaration:**
var name DataType
**Initialization:**
var name DataType = Value
**Example:**
```go
package main
import "fmt"
var hello_world string //Define variable, var <Variable name> <DataType>
var tacos string = "Taco tuesday!!" //Define variable and init, var <Variable name> <DataType> = <Value>
func main() {
hello_world = "Hello, Improvers." // Assign value
fmt.Println(hello_world,tacos) // Print value
}
```
{: file="HelloWorld.go" }
### Multiple declaration & Initialization
Like in another languages to define multiple variables is split the name of the variables whit "," and is the same whit the init.
**Declaration & Initialization:**
var <name>,<name>,<name> <DataType> = <vaule>,<vaule>,<vaule>
**Example:**
```go
package main
import "fmt"
var n1,n2,n3,n4 int = 1,2,3,4
func main() {
fmt.Println(n1,n2,n3,n4) // Print value Output: 1,2,3,4
}
```
{: file="MultipleDeclaration.go" }
### Short declaration
In Golang like in javascript to declare a variable, is necessary use "var" and follow the next variable declaration structure.
var <Variable name> <DataType>
Example:
```go
package main
import "fmt"
func main() {
hello_world := "Hello, Improvers!!"
fmt.Println(hello_world)
}
```
{: file="HelloWorld.go" }
package main
import "fmt"
func main() {
var a = "initial" //variable sin tipo de dato e inizaliciacon
fmt.Println(a)
var b, c int = 1, 2 //Multiple declaracion e inizaliciacon
fmt.Println(b, c)
var d = true e
fmt.Println(d)
var e int //Declaracion in inicializacion
fmt.Println(e)
f := "apple" //Declaración corta
fmt.Println(f)
}
Tipos de datos:
Bool
Aqui no hay mucho de que hablar realmente solo la tipica variabe con 2 estados, True/False.
package main
import "fmt"
func main() {
var a bool // Por defecto esta inicializada con "False"
Operation := 1<2 && 3>1 //True
}
String
Las cadenas existen dos tipos de declaraciónes ( quotes: "", single quoute: '' ).
Propiedades especiales:
//La unica diferencia entre las variables "Quotes" y "single quotes" es que las comillas simples no respetan los comandos de lline \n \t...
import "fmt"
func main() {
var cadena string = "Esto es unda cadena\n con salto de linea"
//Salida:
//Esto es una cadena
//con salto de linea
var cadena string = 'Esto es unda cadena\n con salto de linea'
//Salida:
//Esto es unda cadena\n con salto de linea
}
Integer Signed & Unsigned (Int)
Los integer signed o int* encodea el dato en un rango de [-2147483648 a 2147483647] em 32 bits, A diferecia los datos unsigned o uint* parten del [0 a 4294967295].
Tipo de dato
Descripción
Rango
int
Depende de la plataforma (x32 o x64)
En x32 el rango es 32 bits o 4 bytes con un rango de -2^31 a (2^31 - 1).
En x32 el rango es 64 bits o 8 bytes con un rango de -2^63 a (2^63 - 1)
int8
8 bits/ 1byte
R = -2^7 a ( 2^7 - 1 ) = -128 to 127
int16
16 bits/ 2byte
R = -2^15 a ( 2^15 - 1 )
int32
32 bits/ 4byte
R = -2^31 a ( 2^31 - 1 )
int64
64 bits/ 8byte
R = -2^63 a ( 2^63 - 1 )
uint
Depende de la plataforma (x32 o x64)
En x32 el rango es 32 bits o 4 bytes con un rango de 0 a (2^32 - 1).
En x32 el rango es 64 bits o 8 bytes con un rango de 0 a (2^64 - 1)
uint8
R = 0 a ( 2^8 - 1 ) = 255
uint16
R = 0 a ( 2^16 - 1 )
uint32
R = 0 a ( 2^32 - 1 )
uint64
R = 0 a ( 2^64 - 1 )
uintptr
Este tipo de dato funciona para acceder a la dirección de puntero, por lo cual su tamaño depende de l plataforma (x32 o x64).
En x32 el rango es 32 bits o 4 bytes con un rango de -2^31 a (2^31 - 1).
En x32 el rango es 64 bits o 8 bytes con un rango de -2^63 a (2^63 - 1)
Ejemplo:
package main
import (
"fmt"
"math/cmplx"
)
var (
ToBe bool = false
MaxInt uint64 = 1<<64 - 1
z complex128 = cmplx.Sqrt(-5 + 12i)
)
func main() {
fmt.Printf("Type: %T Value: %v\n", ToBe, ToBe)
fmt.Printf("Type: %T Value: %v\n", MaxInt, MaxInt)
fmt.Printf("Type: %T Value: %v\n", z, z)
}
// Results
Type: bool Value: false
Type: uint64 Value: 18446744073709551615
Type: complex128 Value: (2+3i)
Byte
Dentro de Go Byte es un alias de uint8 esto meciona que es un valor entero. Un uso comun de este tipo de dato es para almacenar cun caracter dado que en Go no existe la varible char.
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
var r byte = 'a'
//Print Size
fmt.Printf("Size: %d\n", unsafe.Sizeof(r))
//Print Type
fmt.Printf("Type: %s\n", reflect.TypeOf(r))
//Print Character
fmt.Printf("Character: %c\n", r)
s := "abc"
//This will the decimal value of byte
fmt.Println([]byte(s))
}
// Output
Size: 1
Type: uint8
Character: a
[97 98 99]
Rune
rune en Go es un alias para int32 significa que es un valor entero. Este valor se usa para almacenar el ID único de los caracteres Unicode o bien llamado Unicode Code Point, si deseas saber más acerca de esto puedes visitar el siguiente blog: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets ( No Excuses! ).
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
r := 'a'
//Print Size
fmt.Printf("Size: %d\n", unsafe.Sizeof(r))
//Print Type
fmt.Printf("Type: %s\n", reflect.TypeOf(r))
//Print Code Point
fmt.Printf("Unicode CodePoint: %U\n", r)
//Print Character
fmt.Printf("Character: %c\n", r)
s := "0b£"
//This will print the Unicode Points
fmt.Printf("%U\n", []rune(s))
//This will the decimal value of Unicode Code Point
fmt.Println([]rune(s))
}
//Output
Size: 4
Type: int32
Unicode CodePoint: U+0061
Character: a
[U+0030 U+0062 U+00A3]
[48 98 163]
Float
Aqui no queda mucho que decir, básicamente números con decimales con 2 longitudes.
Tipo
Rngo
float32
32 bits or 4 bytes
float64
64 bits or 8 bytes
Un detalle importante es que por defecto al hacer una declaración corta esta tomara el valor de x64.
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
//Declare a float64
var a float64 = 2
//Size of float64 in bytes
fmt.Printf("%d bytes\n", unsafe.Sizeof(a))
fmt.Printf("a's type is %s\n", reflect.TypeOf(a))
//Default is float64 when you don't specify a type
b := 2.3
fmt.Printf("b's type is %s\n", reflect.TypeOf(b))
}
//Output
8 bytes
a's type is float64
b's type is float64
Clomplex
El tipo de dato complex nos pertmite realizar operaciónes con el uso de numeros imaginarios.
Tipo
Rngo
complex64
32 bits or 4 bytes
complex128
64 bits or 8 bytes
El default de complex es complex128.
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
var a float32 = 3
var b float32 = 5
//Initialize-1
c := complex(a, b)
//Initialize-2
var d complex64
d = 4 + 5i
//Print Size
fmt.Printf("c's size is %d bytes\n", unsafe.Sizeof(c))
fmt.Printf("d's size is %d bytes\n", unsafe.Sizeof(d))
//Print type
fmt.Printf("c's type is %s\n", reflect.TypeOf(c))
fmt.Printf("d's type is %s\n", reflect.TypeOf(d))
//Operations on complex number
fmt.Println(c+d, c-d, c*d, c/d)
}
//Output
c's size is 8 bytes
d's size is 8 bytes
c's type is complex64
d's type is complex64
(7+10i) (-1+0i) (-13+35i) (0.902439+0.12195122i)
Arrays
Los arrays como en cualquier otro lenguaje de programación solo son un vector y definirlo es igual que los demás lenguajes..
package main
import "fmt"
func main() {
var arr1 [2]int
arr1[0] = "Hi"
arr1[1] = "World"
}
Slices
Un slice podríamos definirlo como un array con tamaño dinámico y flexible. Tambien es posible crear un slice de objetos, pero este necesita ser instanciado antes de usarse como se aprecia en los Maps.
package main
import "fmt"
func main() {
primes := [6]int{2, 3, 5, 7, 11, 13}
var s []int = primes[1:4]
fmt.Println(s)
fmt.Println(s[1])
}
//Output
[3 5 7]
5
Maps 🗺📍
El mapa es la estructura más común en los lenguajes actuales por lo versátil y moldeable. La única diferencia dentro de los mapas en Go es el que se tiene que definir una estructura, la cual mencione que tipo de dato este va a almacenar.
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m map[string]Vertex //Se define la variable, string es el tipo de "key" o "index" y Vertex el tipo de dato
func main() {
m = make(map[string]Vertex) //Para hacer uso de el se tiene que instanciar antes de ser usaado
m["Bell Labs"] = Vertex{
40.68433, -74.39967,
}
fmt.Println(m["Bell Labs"])
}
//Output
{40.68433 -74.39967}