-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdistance.go
54 lines (42 loc) · 1.19 KB
/
distance.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
46
47
48
49
50
51
52
53
54
package unit
import (
"encoding"
"fmt"
)
// Distance is a numerical measurement of physical length.
type Distance float64
var _ encoding.TextUnmarshaler = (*Distance)(nil)
// Meter is the SI unit for measuring Distance.
const Meter Distance = 1
const meterSymbol = "m"
// Mile is a British imperial unit and US customary unit for measuring distance.
const Mile = 1 / 0.621371192 * Kilo * Meter
const mileSymbol = "mi"
// Meters returns d with the unit of m.
func (d Distance) Meters() float64 {
return float64(d)
}
// Get returns d with the unit of as.
func (d Distance) Get(as Distance) float64 {
return float64(d) / float64(as)
}
// String implements fmt.Stringer.
func (d Distance) String() string {
return format(float64(d), meterSymbol)
}
// UnmarshalString sets *d from s.
func (d *Distance) UnmarshalString(s string) error {
parsed, err := parse(s, map[string]float64{
meterSymbol: float64(Meter),
mileSymbol: float64(Mile),
})
if err != nil {
return fmt.Errorf("unmarshal distance: %w", err)
}
*d = Distance(parsed)
return nil
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (d *Distance) UnmarshalText(text []byte) error {
return d.UnmarshalString(string(text))
}