Resumen: Entendiendo los punteros
Parte de la sección Fundamentos del Journey de GO de Coddy. Lección 66 de 109.
Desafío
IntermedioEn este desafío, crearás un sistema sencillo de gestión de inventario para una tienda pequeña. Usarás punteros para actualizar las cantidades del inventario, calcular valores y realizar un seguimiento de los cambios.
Completa las tres funciones siguientes:
-
updateQuantity(quantity *int, change int) (int, bool)
Modifica el valor dequantitysumándolechange(negativo para las ventas, positivo para las reposiciones).
Si el resultado fuera inferior a0, establece*quantityen0en su lugar.
Devuelve la nueva cantidad y un booleano que seatruesi el artículo se ha quedado sin existencias (*quantity == 0). -
calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64
CalculatotalValuecomofloat64(quantity) * price.
SitotalValuees mayor que*highestValue, actualiza*highestValuey establece*mostValuableItemenitemNameusando los punteros.
DevuelvetotalValue. -
displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64)
Imprime el nombre de cada artículo, su cantidad (obtenida mediante la desreferenciación de su puntero) y su valor calculado usandofmt.Printf.
Formato:Apples: 10 (Value: $5.00): usa%.2fpara los precios.
La salida esperada para el inventario inicial es:
Initial Inventory: Apples: 10 (Value: $5.00) Oranges: 15 (Value: $10.50) Bananas: 8 (Value: $2.40) Total inventory value: $17.90 Most valuable item: Oranges
Consejo: Usa *quantity para leer o escribir el valor al que apunta un puntero. Por ejemplo, *quantity += change modifica directamente la variable original.
Pruébalo tú mismo
package main
import "fmt"
// updateQuantity actualiza la cantidad de un artículo y devuelve la nueva cantidad
// y si el artículo está agotado (quantity = 0)
func updateQuantity(quantity *int, change int) (int, bool) {
// TODO: Actualiza el puntero quantity y devuelve el nuevo valor y el estado de agotado
return 0, false
}
// calculateValue calcula el valor total de un artículo basándose en quantity y price
// It also updates the mostValuableItem if this item is more valuable
func calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64 {
// TODO: Calculate the total value, update mostValuableItem if needed, and return the total value
return 0.0
}
// displayInventory imprime los detalles del inventario
// Toma punteros para permitir que la función muestre datos en tiempo real
func displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64) {
fmt.Printf("Apples: %d (Value: $%.2f)\n", *apples, float64(*apples) * applePrice)
fmt.Printf("Oranges: %d (Value: $%.2f)\n", *oranges, float64(*oranges) * orangePrice)
fmt.Printf("Bananas: %d (Value: $%.2f)\n", *bananas, float64(*bananas) * bananaPrice)
}
func main() {
// Inicializar inventario
apples := 10
oranges := 15
bananas := 8
// Precios
applePrice := 0.5 // $0.50 cada uno
orangePrice := 0.7 // $0.70 cada uno
bananaPrice := 0.3 // $0.30 cada uno
// Track the most valuable item
var mostValuableItem string
var highestValue float64
// Display initial inventory
fmt.Println("Initial Inventory:")
displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
// Calculate initial values and find most valuable item
appleValue := calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
orangeValue := calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
bananaValue := calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
fmt.Printf("Most valuable item: %s\n\n", mostValuableItem)
// Simular algunas ventas
fmt.Println("Processing sales...")
_, applesOutOfStock := updateQuantity(&apples, -4) // Vende 4 manzanas
_, orangesOutOfStock := updateQuantity(&oranges, -8) // Vende 8 naranjas
_, bananasOutOfStock := updateQuantity(&bananas, -10) // Intenta vender 10 plátanos (más de los que tenemos)
// Check if any items are out of stock
if applesOutOfStock {
fmt.Println("Apples are out of stock!")
}
if orangesOutOfStock {
fmt.Println("Oranges are out of stock!")
}
if bananasOutOfStock {
fmt.Println("Bananas are out of stock!")
}
// Display updated inventory
fmt.Println("\nUpdated Inventory:")
displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
// Reset most valuable tracking for recalculation
mostValuableItem = ""
highestValue = 0
// Recalcula los valores
appleValue = calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
orangeValue = calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
bananaValue = calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
fmt.Printf("Most valuable item: %s\n\n", mostValuableItem)
// Reabastece los artículos
fmt.Println("Restocking...")
updateQuantity(&apples, 5) // Añade 5 manzanas
updateQuantity(&oranges, 10) // Añade 10 naranjas
updateQuantity(&bananas, 12) // Añade 12 plátanos
// Display final inventory
fmt.Println("\nFinal Inventory:")
displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
// Reset most valuable tracking for final calculation
mostValuableItem = ""
highestValue = 0
// Cálculo final del valor
appleValue = calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
orangeValue = calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
bananaValue = calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
fmt.Printf("Most valuable item: %s\n", mostValuableItem)
}Todas las lecciones de Fundamentos
4Operadores de comparación y lógicos
Operadores de comparación - Parte 1Operadores de comparación - Parte 2Operador lógico ANDOperador lógico OROperador lógico NOTConceptos básicos de precedencia de operadoresResumen: Realizar comparaciones7Flujo de control: Bucles
Explicación del bucle `for`Bucle `for` - BásicoBucle `for` - Solo condiciónLa palabra clave `break`La palabra clave `continue`Bucles anidadosResumen - Repetición de acciones2Variables y tipos de datos básicos
¿Qué es una variable?Inferencia de tipos con `:=`Enteros (int)Números de punto flotanteBooleanosStringsValores ceroConstantesConvenciones de nomenclaturaResumen - Variables y tipos5Entrada y salida básica
Salida con formatoVerbos de formatoImpresión de tiposObtener entrada básica del usuarioResumen: Entrada y salida8Funciones
Comprendiendo las funcionesDeclaración de una funciónLlamada a funcionesParámetros de funciónRetorno de un solo valorRetorno de múltiples valoresValores de retorno con nombreConceptos básicos del alcance de las funcionesResumen: Creando código reutilizable3Operadores básicos
Operadores aritméticosOperador de divisiónEl operador móduloOperador de asignaciónOperadores de asignación compuestaIncremento y decrementoResumen - Cálculos6Flujo de control: Condicionales
La sentencia `if`La palabra clave `else`La palabra clave `else if`Sombreado de variables en `if`Inicialización de variablesLa sentencia `switch``switch` con expresiones`switch` sin expresiónLa palabra clave `fallthrough`Resumen: Toma de decisiones9Punteros
¿Qué es un puntero?Declaración de variables de punteroEl operador de dirección (Address-Of)Desreferenciación de punterosUso de punteros en funcionesPunteros NilResumen: Entendiendo los punterosPractica por tu cuenta: Compilador de Go online