Created
November 9, 2016 02:36
-
-
Save hnakamur/7ef45d868daf2f70a5851d5699d482ad to your computer and use it in GitHub Desktop.
An Go example to read a rational number from yaml.
This file contains 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 ( | |
"log" | |
"math/big" | |
"os" | |
"gopkg.in/yaml.v2" | |
"github.com/pkg/errors" | |
) | |
func main() { | |
exampleYaml := `--- | |
unit_price: 2.1 | |
` | |
var config ExampleConfig | |
err := yaml.Unmarshal([]byte(exampleYaml), &config) | |
if err != nil { | |
log.Printf("%+v", err) | |
os.Exit(1) | |
} | |
log.Printf("%+v", config) | |
} | |
type ExampleConfig struct { | |
UnitPrice Rational `yaml:"unit_price"` | |
} | |
type Rational big.Rat | |
func (o *Rational) UnmarshalYAML(unmarshal func(v interface{}) error) error { | |
var s string | |
err := unmarshal(&s) | |
if err != nil { | |
return err | |
} | |
_, ok := (*big.Rat)(o).SetString(s) | |
if !ok { | |
return errors.Errorf("failed to convert to a rational number: %s", s) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment