Finale: Registro di magazzino
Lezione 47 di 48 del corso Rust per sviluppatori Go di Coddy.
Sfida
MedioAdatta il riferimento completo in Go all’API Rust fornita. L’input contiene fino a 100 righe name delta; i nomi sono parole ASCII minuscole di al massimo 31 byte e i delta vanno da -1000 a 1000. L’input vuoto è valido. Stock::new() -> Stock parte da zero; quantity(&self) -> i32 lo legge; apply(&mut self, delta: i32) -> Result<(), &'static str> rifiuta una quantità risultante negativa con Err("negative"), lasciando invariato lo stato. Ledger::new() -> Ledger parte vuoto; il suo apply(&mut self, name: &str, delta: i32) ha lo stesso contratto per il risultato e non deve creare un elemento mancante in caso di rifiuto. quantity(&self, name: &str) -> Option<i32> distingue un elemento mancante da uno con quantità zero. report(&self) -> String elenca solo le scorte positive nel formato name:quantity, in ordine alfabetico per nome, separate da nuove righe, oppure restituisce empty. Restituisci rejected:N, seguito dal report nelle righe successive. Le chiamate a report non modificano lo stato. La mappa Go memorizza puntatori a valori mutabili di scorta. In Rust, la mappa deve possedere i nomi e i valori di scorta; mantieni la distinzione tra una chiave mancante e una quantità presente pari a zero.
Implementa le API esportate richieste e restituisci il risultato da exercise::solve(input: &str) -> String senza una nuova riga finale. Non stampare nel codice modificabile. Il driver bloccato verifica separatamente le API richieste, legge tutto lo stdin e stampa il testo restituito con una nuova riga finale.
Il tuo codice va inserito in exercise.rs, stock.rs, ledger.rs. main.rs contiene il codice fornito per l’input/output e non può essere modificato.
Riferimento completo in Go per lo stesso contratto di input valido:
package main
import (
"bufio"
"errors"
"fmt"
"os"
"sort"
"strings"
)
type Stock struct { quantity int }
func (s *Stock) Apply(delta int) error {
if s.quantity + delta < 0 { return errors.New("negative") }
s.quantity += delta
return nil
}
func (s Stock) Quantity() int { return s.quantity }
type Ledger struct { rows map[string]*Stock }
func NewLedger() *Ledger { return &Ledger{rows: make(map[string]*Stock)} }
func (l *Ledger) Apply(name string, delta int) error {
stock, exists := l.rows[name]
if !exists { stock = &Stock{} }
if err := stock.Apply(delta); err != nil { return err }
if !exists { l.rows[name] = stock }
return nil
}
func (l *Ledger) Quantity(name string) (int, bool) {
stock, ok := l.rows[name]
if !ok { return 0, false }
return stock.Quantity(), true
}
func (l *Ledger) Report() string {
names := make([]string, 0)
for name, stock := range l.rows {
if stock.Quantity() > 0 { names = append(names, name) }
}
sort.Strings(names)
lines := make([]string, 0, len(names))
for _, name := range names { lines = append(lines, fmt.Sprintf("%s:%d", name, l.rows[name].Quantity())) }
if len(lines) == 0 { return "empty" }
return strings.Join(lines, "\n")
}
func main() {
in := bufio.NewReader(os.Stdin)
ledger := NewLedger()
rejected := 0
for {
var name string
var delta int
if _, err := fmt.Fscan(in, &name, &delta); err != nil { break }
if ledger.Apply(name, delta) != nil { rejected++ }
}
fmt.Printf("rejected:%d\n%s\n", rejected, ledger.Report())
}Provalo tu
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod stock;
mod ledger;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// INIZIO DEI TEST DELL'API PUBBLICA
let mut s = stock::Stock::new(); assert_eq!(s.quantity(), 0);
s.apply(11).unwrap(); assert_eq!(s.apply(-12), Err("negative")); assert_eq!(s.quantity(), 11);
s.apply(-11).unwrap(); assert_eq!(s.quantity(), 0);
let mut l = ledger::Ledger::new(); assert_eq!(l.quantity("held"), None);
assert_eq!(l.apply("held", -8), Err("negative")); assert_eq!(l.quantity("held"), None);
l.apply("held", 17).unwrap(); l.apply("alpha", 2).unwrap();
assert_eq!(l.apply("held", -18), Err("negative")); assert_eq!(l.quantity("held"), Some(17));
assert_eq!(l.report(), "alpha:2\nheld:17"); assert_eq!(l.report(), "alpha:2\nheld:17");
l.apply("alpha", -2).unwrap(); assert_eq!(l.quantity("alpha"), Some(0)); assert_eq!(l.report(), "held:17");
assert_eq!(ledger::Ledger::new().report(), "empty");
// FINE DEI TEST DELL'API PUBBLICA
println!("{}", exercise::solve(&input));
}
Tutte le lezioni di Rust per sviluppatori Go
1Primi programmi in Rust
Eseguire moduli RustOutput e commentiModuli e visibilitàBinding e tipiNumeri e conversioniRiepilogo: fattura di magazzino4Proprietà e prestiti
Proprietà e spostamentiPrestiti condivisiPrestiti mutabiliDurate di vita e visteRiepilogo dei prestiti3Funzioni e sequenze
Funzioni e valori restituitiArray e sezioniVettori e iterazioneRiepilogo: registrare le letture6Assenza ed errore
Option e matchingResult e propagazioneParsing e convalidaContratti degli erroriRiepilogo degli errori9Progetto: Deposito pacchi
Accettazione al depositoReport dei pesi del depositoEsercitati da solo: Compilatore Rust online