Menu
Coddy logo textTech

Recapitulação - Entendendo Ponteiros

Parte da seção Fundamentos do Journey de GO da Coddy. Lição 66 de 109.

challenge icon

Desafio

Médio

Neste desafio, você criará um sistema simples de gerenciamento de estoque para uma pequena loja. Você usará ponteiros para atualizar as quantidades em estoque, calcular valores e acompanhar alterações.

Implemente as três funções abaixo:

  1. updateQuantity(quantity *int, change int) (int, bool)
    Modifique o valor em quantity adicionando change (negativo para vendas, positivo para reposições).
    Se o resultado ficar abaixo de 0, defina *quantity como 0.
    Retorne a nova quantidade e um booleano que seja true se o item estiver agora sem estoque (*quantity == 0).
  2. calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64
    Calcule totalValue como float64(quantity) * price.
    Se totalValue for maior que *highestValue, atualize *highestValue e defina *mostValuableItem como itemName usando os ponteiros.
    Retorne totalValue.
  3. displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64)
    Imprima o nome de cada item, sua quantidade (obtida por desreferenciamento do ponteiro) e seu valor calculado usando fmt.Printf.
    Formato: Apples: 10 (Value: $5.00): use %.2f para os preços.

A saída esperada para o estoque inicial é:

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

Dica: Use *quantity para ler ou escrever o valor para o qual um ponteiro aponta. Por exemplo, *quantity += change modifica diretamente a variável original.

Experimente você mesmo

package main

import "fmt"

// updateQuantity atualiza a quantidade de um item e retorna a nova quantidade
// e se o item está fora de estoque (quantity = 0)
func updateQuantity(quantity *int, change int) (int, bool) {
    // TODO: Atualize o ponteiro quantity e retorne o novo valor e o status de fora de estoque
    return 0, false
}

// calculateValue calcula o valor total de um item com base na quantidade e no preço
// 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 os detalhes do inventário
// Ela recebe ponteiros para permitir que a função mostre dados em tempo 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() {
    // Inicializa o inventário
    apples := 10
    oranges := 15
    bananas := 8
    
    // Preços
    applePrice := 0.5  // $0.50 cada
    orangePrice := 0.7 // $0.70 cada
    bananaPrice := 0.3 // $0.30 cada
    
    // 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)
    
    // Simula algumas vendas
    fmt.Println("Processing sales...")
    _, applesOutOfStock := updateQuantity(&apples, -4) // Vender 4 maçãs
    _, orangesOutOfStock := updateQuantity(&oranges, -8) // Vender 8 laranjas
    _, bananasOutOfStock := updateQuantity(&bananas, -10) // Tentar vender 10 bananas (mais do que temos)
    
    // 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
    
    // Recalcular 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)
    
    // Reabastecer itens
    fmt.Println("Restocking...")
    updateQuantity(&apples, 5)  // Adicionar 5 maçãs
    updateQuantity(&oranges, 10) // Adicionar 10 laranjas
    updateQuantity(&bananas, 12) // Adicionar 12 bananas
    
    // 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 do 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 as lições de Fundamentos

Pratique por conta própria: Compilador de Go online