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ê construirá um sistema simples de gerenciamento de estoque para uma pequena loja. Você usará ponteiros para atualizar as quantidades do estoque, calcular valores e rastrear alterações.

Complete 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 for inferior a 0, defina *quantity como 0.
    Retorne a nova quantidade e um booleano que seja true se o item estiver agora fora de 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, a quantidade (desreferenciada de seu ponteiro) e o valor calculado usando fmt.Printf.
    Formato: Apples: 10 (Value: $5.00) — use %.2f para 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 gravar o valor para o qual um ponteiro aponta. Por exemplo, *quantity += change modifica a variável original diretamente.

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 (quantidade = 0)
func updateQuantity(quantity *int, change int) (int, bool) {
    // TODO: Atualizar o ponteiro da quantidade e retornar 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 preço
// Também atualiza o mostValuableItem se este item for mais valioso
func calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64 {
    // TODO: Calcular o valor total, atualizar mostValuableItem se necessário, e retornar o valor total
    return 0.0
}

// displayInventory imprime os detalhes do inventário
// 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() {
    // Inicializar 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
    
    // Rastrear o item mais valioso
    var mostValuableItem string
    var highestValue float64
    
    // Exibir inventário inicial
    fmt.Println("Initial Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Calcular valores iniciais e encontrar o item mais valioso
    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 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)
    
    // Verificar se algum item está fora de estoque
    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!")
    }
    
    // Exibir inventário atualizado
    fmt.Println("\nUpdated Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Resetar rastreamento do mais valioso para recalcular
    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)
    
    // Repor itens
    fmt.Println("Restocking...")
    updateQuantity(&apples, 5)  // Adicionar 5 maçãs
    updateQuantity(&oranges, 10) // Adicionar 10 laranjas
    updateQuantity(&bananas, 12) // Adicionar 12 bananas
    
    // Exibir inventário final
    fmt.Println("\nFinal Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Resetar rastreamento do mais valioso para o cálculo final
    mostValuableItem = ""
    highestValue = 0
    
    // Cálculo do valor final
    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