-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathgetter.go
45 lines (38 loc) · 975 Bytes
/
getter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Copyright (c) Efficient Go Authors
// Licensed under the Apache License 2.0.
package getter
type Report interface {
Error() error
}
type ReportGetter interface {
Get() []Report
}
// FailureRatio represents slightly less efficient (also less safe) use of getters.
// Read more in "Efficient Go"; Example 1-1.
func FailureRatio(reports ReportGetter) float64 {
if len(reports.Get()) == 0 {
return 0
}
var sum float64
for _, report := range reports.Get() {
if report.Error() != nil {
sum++
}
}
return sum / float64(len(reports.Get()))
}
// FailureRatio_Better represents more efficient (also safer and more readable) use of getters.
// Read more in "Efficient Go"; Example 1-2 (called `FailureRatio` in example).
func FailureRatio_Better(reports ReportGetter) float64 {
got := reports.Get()
if len(got) == 0 {
return 0
}
var sum float64
for _, report := range got {
if report.Error() != nil {
sum++
}
}
return sum / float64(len(got))
}