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

learning/go-patterns/patterns/interfaces/interfaces.go

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

跳到函数 / 声明
// Package interfaces demonstrates consumer-defined, minimal interfaces.
package interfaces

// Product is the value returned by a Catalog.
type Product struct {
	Name       string
	PriceCents int
}

// Catalog is the only behavior needed by the pricing functions.
type Catalog interface {
	Find(name string) (Product, bool)
}

// CatalogFunc adapts a function to Catalog, avoiding a one-method struct in tests
// and small integrations.
type CatalogFunc func(name string) (Product, bool)

// Find implements Catalog.
func (f CatalogFunc) Find(name string) (Product, bool) {
	return f(name)
}

// PriceOf looks up one product through the smallest useful interface.
func PriceOf(catalog Catalog, name string) (int, bool) {
	if catalog == nil {
		return 0, false
	}
	product, ok := catalog.Find(name)
	if !ok {
		return 0, false
	}
	return product.PriceCents, true
}

// Total adds the prices of all requested products. It returns no partial total
// when any product is missing.
func Total(catalog Catalog, names []string) (int, bool) {
	if catalog == nil {
		return 0, false
	}

	total := 0
	for _, name := range names {
		product, ok := catalog.Find(name)
		if !ok {
			return 0, false
		}
		total += product.PriceCents
	}
	return total, true
}