Created
February 20, 2017 08:34
-
-
Save odeke-em/820cf7ab70410826187ec6322a452f73 to your computer and use it in GitHub Desktop.
full snippet for the earthquakes compile type assertions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"fmt" | |
"log" | |
"strconv" | |
) | |
func main() { | |
jsonOfCoordinates := []string{ | |
"[10.84, 482.118, 45000]", | |
"[45.84, 99.118]", | |
"[-54, 10.84, 48218, 45000]", | |
} | |
for i, jsonStr := range jsonOfCoordinates { | |
c := new(Coordinate) | |
if err := json.Unmarshal([]byte(jsonStr), c); err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("#%d: Latitude: %f Longitude: %f Depth: %f\n", i, c.Latitude, c.Longitude, c.Depth) | |
} | |
} | |
type Coordinate struct { | |
Latitude float32 `json:"latitude"` | |
Longitude float32 `json:"longitude"` | |
Depth float32 `json:"depth"` | |
} | |
var ( | |
lBrace = []byte("[") | |
rBrace = []byte("]") | |
comma = []byte(",") | |
) | |
var _ json.Unmarshaler = (*Coordinate)(nil) | |
func (c *Coordinate) UnmarshalJSON(b []byte) error { | |
b = bytes.TrimSpace(b) | |
b = bytes.TrimPrefix(b, lBrace) | |
b = bytes.TrimSuffix(b, rBrace) | |
splits := bytes.Split(b, comma) | |
var cleaned [][]byte | |
for _, split := range splits { | |
cleaned = append(cleaned, bytes.TrimSpace(split)) | |
} | |
ptrsToSet := [...]*float32{ | |
0: &c.Longitude, | |
1: &c.Latitude, | |
2: &c.Depth, | |
} | |
for i, ptr := range ptrsToSet { | |
if i >= len(cleaned) { // Done receiving values | |
break | |
} | |
f64, err := strconv.ParseFloat(string(cleaned[i]), 32) | |
if err != nil { | |
return err | |
} | |
*ptr = float32(f64) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment