Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 package model | 1 package model |
| 2 | 2 |
| 3 import ( | 3 import ( |
| 4 "bytes" | 4 "bytes" |
| 5 "math" | 5 "math" |
| 6 "strconv" | 6 "strconv" |
| 7 ) | 7 ) |
| 8 | 8 |
| 9 func round(f float64) int { | 9 func round(f float64) int { |
| 10 if math.Abs(f) < 0.5 { | 10 if math.Abs(f) < 0.5 { |
| 11 return 0 | 11 return 0 |
| 12 } | 12 } |
| 13 return int(f + math.Copysign(0.5, f)) | 13 return int(f + math.Copysign(0.5, f)) |
| 14 } | 14 } |
| 15 | 15 |
| 16 // TestNode is a node in a Tests tree. | 16 // Node is a node in a Tests tree. |
| 17 type TestNode interface { | 17 // |
| 18 » // Children returns a map of a TestNode's children. | 18 // In reality, it as almost as weak as empty interface, |
|
estaab
2016/08/12 15:17:20
Interesting, is this a common pattern in go?
nishanths
2016/08/12 16:45:58
I may have seen it elsewhere, but don't remember w
| |
| 19 » Children() map[string]TestNode | 19 // but the unexported method allow the package to achieve |
| 20 | 20 // type safety internally. |
| 21 » testnode() | 21 type Node interface { |
| 22 » node() | |
| 22 } | 23 } |
| 23 | 24 |
| 24 // number is an integer that supports JSON unmarshaling from a string | 25 // Number is an integer that supports JSON unmarshaling from a string |
| 25 // and marshaling back to a string. | 26 // and marshaling back to a string. |
| 26 type number int | 27 type Number int |
| 27 | 28 |
| 28 func (n *number) UnmarshalJSON(data []byte) error { | 29 // UnmarshalJSON unmarshals data into n. |
| 30 // data is expected to be a JSON string. If the string | |
| 31 // fails to parse to an integer, UnmarshalJSON returns | |
| 32 // an error. | |
| 33 func (n *Number) UnmarshalJSON(data []byte) error { | |
| 29 data = bytes.Trim(data, `"`) | 34 data = bytes.Trim(data, `"`) |
| 30 num, err := strconv.Atoi(string(data)) | 35 num, err := strconv.Atoi(string(data)) |
| 31 if err != nil { | 36 if err != nil { |
| 32 return err | 37 return err |
| 33 } | 38 } |
| 34 » *n = number(num) | 39 » *n = Number(num) |
| 35 return nil | 40 return nil |
| 36 } | 41 } |
| 37 | 42 |
| 38 func (n *number) MarshalJSON() ([]byte, error) { | 43 // MarshalJSON marshals n into JSON string. |
| 44 func (n *Number) MarshalJSON() ([]byte, error) { | |
| 39 return []byte(strconv.Itoa(int(*n))), nil | 45 return []byte(strconv.Itoa(int(*n))), nil |
| 40 } | 46 } |
| OLD | NEW |