Podemos definir una variable indicando el tipo de dato
var int myVar
myVar = 64
O podemos utilizar el dos puntos igual (:=) para instanciar y asignar al mismo tiempo, va a tomar el tipo de dato del valor que le pasamos
myVar := 64
var int64 myVar
myVar = 64
Tipo | Tamaño | Rango |
---|---|---|
int8 | 8 bits | -128 hasta 127 |
int16 | 16 bits | -215 hasta 215 -1 |
int32 | 32 bits | -231 hasta 231 -1 |
int64 | 64 bits | -263 hasta 263 -1 |
int | Depende plataforma | Depende plataforma |
var uint64 myVar
myVar = 64
Tipo | Tamaño | Rango |
---|---|---|
uint8 | 8 bits | 0 hasta 255 |
uint16 | 16 bits | 0 hasta 216 -1 |
uint32 | 32 bits | 0 hasta 232 -1 |
uint64 | 64 bits | 0 hasta 264 -1 |
uint | Depende plataforma | Depende plataforma |
var float64 myVar
myVar = 64.55
Tipo | Tamaño |
---|---|
float32 | 32 bits |
float64 | 64 bits |
Los strings son cadenas de bytes
var string myVar
myVar = "My string"
A | B | A or B |
---|---|---|
false | false | false |
false | true | true |
true | false | true |
true | true | true |
myValue1 := 3
myValue2 := 5
fmt.Println(myValue1 == myValue2 || myValue1 < myValue2) // (false or true) = true
A | B | A and B |
---|---|---|
false | false | false |
false | true | false |
true | false | false |
true | true | true |
myValue1 := 3
myValue2 := 5
fmt.Println(myValue1 == myValue2 && myValue1 < myValue2) // (false and true) = false
Tamaño fijo
var myArrayVar [6]int
fmt.Println(myArrayVar)
myArrayVar1 := [3]string{"value1", "value2", "value3"}
fmt.Println(myArrayVar1)
myArrayVar[1] = 2
myArrayVar[2] = 5
myArrayVar[3] = 9
fmt.Println(myArrayVar)
Tamaño dinamico
var slice1 []int
slice1 = append(slice1, 10, 20, 30, 40, 50)
fmt.Printf("size: %d, value %v\n", len(slice1), slice1)
// Declaracion e instancia de la variable
m1 := make(map[int]string)
// Asignamos valores
m1[1] = "A"
m1[2] = "B"
m1[3] = "C"
// Mostramos el valor de la key 1
fmt.Println(m1[1])
sum := 0
for i := 0; i < 10; i++ {
sum++
}
arr := []int{1, 2, 3, 1, 2, 3}
for i, v := range arr {
fmt.Println("Index: ",i ," - Value: ", v)
}
map2 := map[string]float64{
"A": 12.3,
"Z": 23.1,
"C": 34,
}
for key, value := range map2 {
fmt.Println("Key:", key, "Value:", value)
}
// x, y are int parameters & return int value
func MiFunction(x, y int) int {
return x + y
}