PPysolate SpineREAD THE CODE · UNDERSTAND THE SYSTEM
课程与章节
源码索引 / CURRENT IMPLEMENTATION

learning/go-patterns/stages/01-sync/main.go

51 行 · 点击行号可定位;函数链接随声明位置更新,不手填行号。

跳到函数 / 声明
// Stage 01 keeps the price source concrete so the call path is easy to see.
// Run it with: go run .
package main

import "fmt"

// Price stores money in cents. An integer keeps arithmetic predictable.
type Price struct {
	Item  string
	Cents int
}

// Catalog is the only data source needed at this stage.
type Catalog map[string]Price

// Service owns the operation exposed to the caller.
type Service struct {
	catalog Catalog
}

func NewService(catalog Catalog) Service {
	return Service{catalog: catalog}
}

// Quote performs one synchronous lookup: the caller waits for the answer.
func (s Service) Quote(item string) (Price, error) {
	price, ok := s.catalog[item]
	if !ok {
		return Price{}, fmt.Errorf("item %q is not in the catalog", item)
	}
	return price, nil
}

func main() {
	service := NewService(Catalog{
		"book": {Item: "book", Cents: 2100},
		"pen":  {Item: "pen", Cents: 300},
	})

	price, err := service.Quote("book")
	if err != nil {
		fmt.Println("quote failed:", err)
		return
	}
	fmt.Printf("%s: %d cents\n", price.Item, price.Cents)

	if _, err := service.Quote("notebook"); err != nil {
		fmt.Println("missing item:", err)
	}

}