Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Created November 9, 2016 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnakamur/7ef45d868daf2f70a5851d5699d482ad to your computer and use it in GitHub Desktop.
Save hnakamur/7ef45d868daf2f70a5851d5699d482ad to your computer and use it in GitHub Desktop.
An Go example to read a rational number from yaml.
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