Operadores
## Objetivos de Aprendizaje
- Dominar operadores aritméticos
- Comprender operadores de comparación
- Aprender operadores lógicos
- Trabajar con operadores bit a bit
- Comprender la precedencia de operadores
## Operadores Aritméticos
### Operaciones Básicas
```go
a, b := 10, 3
fmt.Println(a + b) // 13 (suma)
fmt.Println(a - b) // 7 (resta)
fmt.Println(a * b) // 30 (multiplicación)
fmt.Println(a / b) // 3 (división entera)
fmt.Println(a % b) // 1 (módulo/resto)
```
### Comportamiento de la División
```go
// La división entera trunca hacia cero
fmt.Println(10 / 3) // 3, no 3.333...
// Para división de punto flotante
fmt.Println(10.0 / 3.0) // 3.333...
```
### Incremento/Decremento
```go
x := 5
x++ // x = 6 (equivalente a x += 1)
x-- // x = 5 (equivalente a x -= 1)
// El comportamiento pre/post es el mismo - no retorna valor
fmt.Println(x) // 5
```
### Asignación Compuesta
```go
x := 10
x += 5 // x = 15
x -= 3 // x = 12
x *= 2 // x = 24
x /= 4 // x = 6
x %= 5 // x = 1
```
## Operadores de Comparación
### Operadores Relacionales
```go
a, b := 5, 10
fmt.Println(a == b) // false (igual)
fmt.Println(a != b) // true (no igual)
fmt.Println(a < b) // true (menor que)
fmt.Println(a > b) // false (mayor que)
fmt.Println(a <= b) // true (menor o igual)
fmt.Println(a >= b) // false (mayor o igual)
```
### Nota Importante
```go
// = es asignación
// == es comparación
x := 5
if x == 5 { // Correcto: compara x con 5
fmt.Println("x es 5")
}
```
## Operadores Lógicos
### AND, OR, NOT
```go
a, b := true, false
fmt.Println(a && b) // false (AND - ambos deben ser verdaderos)
fmt.Println(a || b) // true (OR - uno debe ser verdadero)
fmt.Println(!a) // false (NOT - invierte)
```
### Evaluación de Cortocircuito
```go
x := 0
// && se detiene si el primero es falso
if x != 0 && y/x > 2 { // Seguro - no dividirá por cero
fmt.Println("seguro")
}
// || se detiene si el primero es verdadero
if obj == nil || obj.isValid() { // Seguro - no llamará en nil
fmt.Println("seguro")
}
```
### Tabla de Verdad
| A | B | A && B | A \|\| B | !A |
|---|---|--------|----------|-----|
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |
## Operadores Bit a Bit
### Operaciones Binarias
```go
a, b := 5, 3 // 101 y 011 en binario
fmt.Println(a & b) // 1 (AND: 101 & 011 = 001)
fmt.Println(a | b) // 7 (OR: 101 | 011 = 111)
fmt.Println(a ^ b) // 6 (XOR: 101 ^ 011 = 110)
fmt.Println(^a) // -6 (NOT: ^101 = ...010 = -6)
fmt.Println(a << 1) // 10 (desplazamiento izquierda: 101 << = 1010)
fmt.Println(a >> 1) // 2 (desplazamiento derecha: 101 >> = 10)
```
### Asignación Bit a Bit
```go
x := 10
x &= 3 // x = x & 3
x |= 3 // x = x | 3
x ^= 3 // x = x ^ 3
x <<= 2 // x = x << 2
x >>= 1 // x = x >> 1
```
### Usos Comunes
```go
// Verificar si un bit está establecido
flags := 0b1010 // 10 en decimal
if flags & 0b1000 != 0 {
fmt.Println("Bit 3 está establecido")
}
// Establecer un bit
flags = flags | 0b0001
// Cambiar un bit
flags = flags ^ 0b0100
// Limpiar un bit
flags = flags &^ 0b0100
```
## Operadores de Dirección
### Operaciones de Punteros
```go
x := 10
p := &x // Obtener dirección de x
fmt.Println(p) // Dirección de memoria (ej. 0xc00000a008)
fmt.Println(*p) // 10 (desreferenciar)
*p = 20 // Cambiar valor a través del puntero
fmt.Println(x) // 20
```
### Operador New
```go
p := new(int) // Crea puntero a int con valor cero
fmt.Println(*p) // 0
```
## Operadores de Canal
### Creación y Operaciones de Canal
```go
ch := make(chan int)
// Enviar y recibir
ch <- 10 // Enviar 10 al canal
value := <-ch // Recibir del canal
```
## Precedencia de Operadores
### De Mayor a Menor
| Prioridad | Operadores |
|----------|-------------------|
| 1 | `*`, `/`, `%`, `<<`, `>>`, `&`, `&^` |
| 2 | `+`, `-`, `\|`, `^` |
| 3 | `==`, `!=`, `<`, `<=`, `>`, `>=` |
| 4 | `<-` (canal) |
| 5 | `&&` |
| 6 | `\|\|` |
### Usar Paréntesis
```go
// Precedencia clara
if (a > b) && (c < d) {
fmt.Println("Ambas condiciones son verdaderas")
}
// Mismo resultado, menos claro
if a > b && c < d {
fmt.Println("Ambas condiciones son verdaderas")
}
```
## Operadores de Aserción de Tipo
### Tipo Switch
```go
var i interface{} = "hello"
switch v := i.(type) {
case int:
fmt.Printf("Entero: %d\n", v)
case string:
fmt.Printf("Cadena: %s\n", v)
default:
fmt.Printf("Tipo desconocido\n")
}
```
### Aserción de Tipo
```go
var i interface{} = "hello"
s := i.(string) // Panics si no es string
s, ok := i.(string) // Seguro: ok es false si no es string
```
## Resumen
- Aritméticos: `+`, `-`, `*`, `/`, `%`
- Incremento/Decremento: `++`, `--`
- Comparación: `==`, `!=`, `<`, `>`, `<=`, `>=`
- Lógicos: `&&`, `||`, `!`
- Bit a bit: `&`, `|`, `^`, `~`, `<<`, `>>`
- Asignación: `=`, `+=`, `-=`, etc.
- Puntero: `&` (dirección), `*` (desreferencia)
- Canal: `<-` (enviar/recibir)
- Usar paréntesis para aclarar precedencia
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →