func (d *Decoder) valueFromToml(mtype reflect.Type, tval interface{}) (reflect.Value, error) {
	if mtype.Kind() == reflect.Ptr {
		return d.unwrapPointer(mtype, tval)
	}
	switch t := tval.(type) {
	case *Tree:
		if isTree(mtype) {
			return d.valueFromTree(mtype, t)
		}
		return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to a tree", tval, tval)
	case []*Tree:
		if isTreeSlice(mtype) {
			return d.valueFromTreeSlice(mtype, t)
		}
		return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to trees", tval, tval)
	case []interface{}:
		if isOtherSlice(mtype) {
			return d.valueFromOtherSlice(mtype, t)
		}
		return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to a slice", tval, tval)
	default:
		switch mtype.Kind() {
		case reflect.Bool, reflect.Struct:
			val := reflect.ValueOf(tval)
			if !val.Type().ConvertibleTo(mtype) {
				return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to %v", tval, tval, mtype.String())
			}
			return val.Convert(mtype), nil
		case reflect.String:
			val := reflect.ValueOf(tval)
			if !val.Type().ConvertibleTo(mtype) || val.Kind() == reflect.Int64 {
				return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to %v", tval, tval, mtype.String())
			}
			return val.Convert(mtype), nil
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			val := reflect.ValueOf(tval)
			if mtype.Kind() == reflect.Int64 && mtype == reflect.TypeOf(time.Duration(1)) && val.Kind() == reflect.String {
				d, err := time.ParseDuration(val.String())
				if err != nil {
					return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to %v. %s", tval, tval, mtype.String(), err)
				}
				return reflect.ValueOf(d), nil
			}
			if !val.Type().ConvertibleTo(mtype) {
				return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to %v", tval, tval, mtype.String())
			}
			if reflect.Indirect(reflect.New(mtype)).OverflowInt(val.Convert(mtype).Int()) {
				return reflect.ValueOf(nil), fmt.Errorf("%v(%T) would overflow %v", tval, tval, mtype.String())
			}
			return val.Convert(mtype), nil
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
			val := reflect.ValueOf(tval)
			if !val.Type().ConvertibleTo(mtype) {
				return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to %v", tval, tval, mtype.String())
			}
			if val.Convert(reflect.TypeOf(int(1))).Int() < 0 {
				return reflect.ValueOf(nil), fmt.Errorf("%v(%T) is negative so does not fit in %v", tval, tval, mtype.String())
			}
			if reflect.Indirect(reflect.New(mtype)).OverflowUint(uint64(val.Convert(mtype).Uint())) {
				return reflect.ValueOf(nil), fmt.Errorf("%v(%T) would overflow %v", tval, tval, mtype.String())
			}
			return val.Convert(mtype), nil
		case reflect.Float32, reflect.Float64:
			val := reflect.ValueOf(tval)
			if !val.Type().ConvertibleTo(mtype) {
				return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to %v", tval, tval, mtype.String())
			}
			if reflect.Indirect(reflect.New(mtype)).OverflowFloat(val.Convert(mtype).Float()) {
				return reflect.ValueOf(nil), fmt.Errorf("%v(%T) would overflow %v", tval, tval, mtype.String())
			}
			return val.Convert(mtype), nil
		default:
			return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to %v(%v)", tval, tval, mtype, mtype.Kind())
		}
	}
}
Convert toml value to marshal value, using marshal type
package toml
import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"reflect"
	"sort"
	"strconv"
	"strings"
	"time"
)
const (
	tagFieldName    = "toml"
	tagFieldComment = "comment"
	tagCommented    = "commented"
	tagMultiline    = "multiline"
	tagDefault      = "default"
)
type tomlOpts struct {
	name         string
	comment      string
	commented    bool
	multiline    bool
	include      bool
	omitempty    bool
	defaultValue string
}
type encOpts struct {
	quoteMapKeys            bool
	arraysOneElementPerLine bool
}
var encOptsDefaults = encOpts{
	quoteMapKeys: false,
}
type annotation struct {
	tag          string
	comment      string
	commented    string
	multiline    string
	defaultValue string
}
var annotationDefault = annotation{
	tag:          tagFieldName,
	comment:      tagFieldComment,
	commented:    tagCommented,
	multiline:    tagMultiline,
	defaultValue: tagDefault,
}
type marshalOrder int
const (
	OrderAlphabetical marshalOrder = iota + 1
	OrderPreserve
)
var timeType = reflect.TypeOf(time.Time{})
var marshalerType = reflect.TypeOf(new(Marshaler)).Elem()
func isPrimitive(mtype reflect.Type) bool {
	switch mtype.Kind() {
	case reflect.Ptr:
		return isPrimitive(mtype.Elem())
	case reflect.Bool:
		return true
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return true
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return true
	case reflect.Float32, reflect.Float64:
		return true
	case reflect.String:
		return true
	case reflect.Struct:
		return mtype == timeType || isCustomMarshaler(mtype)
	default:
		return false
	}
}
func isTreeSlice(mtype reflect.Type) bool {
	switch mtype.Kind() {
	case reflect.Slice:
		return !isOtherSlice(mtype)
	default:
		return false
	}
}
func isOtherSlice(mtype reflect.Type) bool {
	switch mtype.Kind() {
	case reflect.Ptr:
		return isOtherSlice(mtype.Elem())
	case reflect.Slice:
		return isPrimitive(mtype.Elem()) || isOtherSlice(mtype.Elem())
	default:
		return false
	}
}
func isTree(mtype reflect.Type) bool {
	switch mtype.Kind() {
	case reflect.Map:
		return true
	case reflect.Struct:
		return !isPrimitive(mtype)
	default:
		return false
	}
}
func isCustomMarshaler(mtype reflect.Type) bool {
	return mtype.Implements(marshalerType)
}
func callCustomMarshaler(mval reflect.Value) ([]byte, error) {
	return mval.Interface().(Marshaler).MarshalTOML()
}
type Marshaler interface {
	MarshalTOML() ([]byte, error)
}
func Marshal(v interface{}) ([]byte, error) {
	return NewEncoder(nil).marshal(v)
}
type Encoder struct {
	w io.Writer
	encOpts
	annotation
	line  int
	col   int
	order marshalOrder
}
func NewEncoder(w io.Writer) *Encoder {
	return &Encoder{
		w:          w,
		encOpts:    encOptsDefaults,
		annotation: annotationDefault,
		line:       0,
		col:        1,
		order:      OrderAlphabetical,
	}
}
func (e *Encoder) Encode(v interface{}) error {
	b, err := e.marshal(v)
	if err != nil {
		return err
	}
	if _, err := e.w.Write(b); err != nil {
		return err
	}
	return nil
}
func (e *Encoder) QuoteMapKeys(v bool) *Encoder {
	e.quoteMapKeys = v
	return e
}
func (e *Encoder) ArraysWithOneElementPerLine(v bool) *Encoder {
	e.arraysOneElementPerLine = v
	return e
}
func (e *Encoder) Order(ord marshalOrder) *Encoder {
	e.order = ord
	return e
}
func (e *Encoder) SetTagName(v string) *Encoder {
	e.tag = v
	return e
}
func (e *Encoder) SetTagComment(v string) *Encoder {
	e.comment = v
	return e
}
func (e *Encoder) SetTagCommented(v string) *Encoder {
	e.commented = v
	return e
}
func (e *Encoder) SetTagMultiline(v string) *Encoder {
	e.multiline = v
	return e
}
func (e *Encoder) marshal(v interface{}) ([]byte, error) {
	mtype := reflect.TypeOf(v)
	switch mtype.Kind() {
	case reflect.Struct, reflect.Map:
	case reflect.Ptr:
		if mtype.Elem().Kind() != reflect.Struct {
			return []byte{}, errors.New("Only pointer to struct can be marshaled to TOML")
		}
	default:
		return []byte{}, errors.New("Only a struct or map can be marshaled to TOML")
	}
	sval := reflect.ValueOf(v)
	if isCustomMarshaler(mtype) {
		return callCustomMarshaler(sval)
	}
	t, err := e.valueToTree(mtype, sval)
	if err != nil {
		return []byte{}, err
	}
	var buf bytes.Buffer
	_, err = t.writeToOrdered(&buf, "", "", 0, e.arraysOneElementPerLine, e.order)
	return buf.Bytes(), err
}
func (e *Encoder) nextTree() *Tree {
	return newTreeWithPosition(Position{Line: e.line, Col: 1})
}
func (e *Encoder) valueToTree(mtype reflect.Type, mval reflect.Value) (*Tree, error) {
	if mtype.Kind() == reflect.Ptr {
		return e.valueToTree(mtype.Elem(), mval.Elem())
	}
	tval := e.nextTree()
	switch mtype.Kind() {
	case reflect.Struct:
		for i := 0; i < mtype.NumField(); i++ {
			mtypef, mvalf := mtype.Field(i), mval.Field(i)
			opts := tomlOptions(mtypef, e.annotation)
			if opts.include && (!opts.omitempty || !isZero(mvalf)) {
				val, err := e.valueToToml(mtypef.Type, mvalf)
				if err != nil {
					return nil, err
				}
				tval.SetWithOptions(opts.name, SetOptions{
					Comment:   opts.comment,
					Commented: opts.commented,
					Multiline: opts.multiline,
				}, val)
			}
		}
	case reflect.Map:
		keys := mval.MapKeys()
		if e.order == OrderPreserve && len(keys) > 0 {
			typ := keys[0].Type()
			kind := keys[0].Kind()
			if kind == reflect.String {
				ikeys := make([]string, len(keys))
				for i := range keys {
					ikeys[i] = keys[i].Interface().(string)
				}
				sort.Strings(ikeys)
				for i := range ikeys {
					keys[i] = reflect.ValueOf(ikeys[i]).Convert(typ)
				}
			}
		}
		for _, key := range keys {
			mvalf := mval.MapIndex(key)
			val, err := e.valueToToml(mtype.Elem(), mvalf)
			if err != nil {
				return nil, err
			}
			if e.quoteMapKeys {
				keyStr, err := tomlValueStringRepresentation(key.String(), "", e.arraysOneElementPerLine)
				if err != nil {
					return nil, err
				}
				tval.SetPath([]string{keyStr}, val)
			} else {
				tval.Set(key.String(), val)
			}
		}
	}
	return tval, nil
}
func (e *Encoder) valueToTreeSlice(mtype reflect.Type, mval reflect.Value) ([]*Tree, error) {
	tval := make([]*Tree, mval.Len(), mval.Len())
	for i := 0; i < mval.Len(); i++ {
		val, err := e.valueToTree(mtype.Elem(), mval.Index(i))
		if err != nil {
			return nil, err
		}
		tval[i] = val
	}
	return tval, nil
}
func (e *Encoder) valueToOtherSlice(mtype reflect.Type, mval reflect.Value) (interface{}, error) {
	tval := make([]interface{}, mval.Len(), mval.Len())
	for i := 0; i < mval.Len(); i++ {
		val, err := e.valueToToml(mtype.Elem(), mval.Index(i))
		if err != nil {
			return nil, err
		}
		tval[i] = val
	}
	return tval, nil
}
func (e *Encoder) valueToToml(mtype reflect.Type, mval reflect.Value) (interface{}, error) {
	e.line++
	if mtype.Kind() == reflect.Ptr {
		return e.valueToToml(mtype.Elem(), mval.Elem())
	}
	switch {
	case isCustomMarshaler(mtype):
		return callCustomMarshaler(mval)
	case isTree(mtype):
		return e.valueToTree(mtype, mval)
	case isTreeSlice(mtype):
		return e.valueToTreeSlice(mtype, mval)
	case isOtherSlice(mtype):
		return e.valueToOtherSlice(mtype, mval)
	default:
		switch mtype.Kind() {
		case reflect.Bool:
			return mval.Bool(), nil
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			if mtype.Kind() == reflect.Int64 && mtype == reflect.TypeOf(time.Duration(1)) {
				return fmt.Sprint(mval), nil
			}
			return mval.Int(), nil
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			return mval.Uint(), nil
		case reflect.Float32, reflect.Float64:
			return mval.Float(), nil
		case reflect.String:
			return mval.String(), nil
		case reflect.Struct:
			return mval.Interface().(time.Time), nil
		default:
			return nil, fmt.Errorf("Marshal can't handle %v(%v)", mtype, mtype.Kind())
		}
	}
}
func (t *Tree) Unmarshal(v interface{}) error {
	d := Decoder{tval: t, tagName: tagFieldName}
	return d.unmarshal(v)
}
func (t *Tree) Marshal() ([]byte, error) {
	var buf bytes.Buffer
	err := NewEncoder(&buf).Encode(t)
	return buf.Bytes(), err
}
func Unmarshal(data []byte, v interface{}) error {
	t, err := LoadReader(bytes.NewReader(data))
	if err != nil {
		return err
	}
	return t.Unmarshal(v)
}
type Decoder struct {
	r    io.Reader
	tval *Tree
	encOpts
	tagName string
}
func NewDecoder(r io.Reader) *Decoder {
	return &Decoder{
		r:       r,
		encOpts: encOptsDefaults,
		tagName: tagFieldName,
	}
}
func (d *Decoder) Decode(v interface{}) error {
	var err error
	d.tval, err = LoadReader(d.r)
	if err != nil {
		return err
	}
	return d.unmarshal(v)
}
func (d *Decoder) SetTagName(v string) *Decoder {
	d.tagName = v
	return d
}
func (d *Decoder) unmarshal(v interface{}) error {
	mtype := reflect.TypeOf(v)
	if mtype.Kind() != reflect.Ptr {
		return errors.New("only a pointer to struct or map can be unmarshaled from TOML")
	}
	elem := mtype.Elem()
	switch elem.Kind() {
	case reflect.Struct, reflect.Map:
	default:
		return errors.New("only a pointer to struct or map can be unmarshaled from TOML")
	}
	sval, err := d.valueFromTree(elem, d.tval)
	if err != nil {
		return err
	}
	reflect.ValueOf(v).Elem().Set(sval)
	return nil
}
func (d *Decoder) valueFromTree(mtype reflect.Type, tval *Tree) (reflect.Value, error) {
	if mtype.Kind() == reflect.Ptr {
		return d.unwrapPointer(mtype, tval)
	}
	var mval reflect.Value
	switch mtype.Kind() {
	case reflect.Struct:
		mval = reflect.New(mtype).Elem()
		for i := 0; i < mtype.NumField(); i++ {
			mtypef := mtype.Field(i)
			an := annotation{tag: d.tagName}
			opts := tomlOptions(mtypef, an)
			if opts.include {
				baseKey := opts.name
				keysToTry := []string{
					baseKey,
					strings.ToLower(baseKey),
					strings.ToTitle(baseKey),
					strings.ToLower(string(baseKey[0])) + baseKey[1:],
				}
				found := false
				for _, key := range keysToTry {
					exists := tval.Has(key)
					if !exists {
						continue
					}
					val := tval.Get(key)
					mvalf, err := d.valueFromToml(mtypef.Type, val)
					if err != nil {
						return mval, formatError(err, tval.GetPosition(key))
					}
					mval.Field(i).Set(mvalf)
					found = true
					break
				}
				if !found && opts.defaultValue != "" {
					mvalf := mval.Field(i)
					var val interface{}
					var err error
					switch mvalf.Kind() {
					case reflect.Bool:
						val, err = strconv.ParseBool(opts.defaultValue)
						if err != nil {
							return mval.Field(i), err
						}
					case reflect.Int:
						val, err = strconv.Atoi(opts.defaultValue)
						if err != nil {
							return mval.Field(i), err
						}
					case reflect.String:
						val = opts.defaultValue
					case reflect.Int64:
						val, err = strconv.ParseInt(opts.defaultValue, 10, 64)
						if err != nil {
							return mval.Field(i), err
						}
					case reflect.Float64:
						val, err = strconv.ParseFloat(opts.defaultValue, 64)
						if err != nil {
							return mval.Field(i), err
						}
					default:
						return mval.Field(i), fmt.Errorf("unsuported field type for default option")
					}
					mval.Field(i).Set(reflect.ValueOf(val))
				}
			}
		}
	case reflect.Map:
		mval = reflect.MakeMap(mtype)
		for _, key := range tval.Keys() {
			val := tval.GetPath([]string{key})
			mvalf, err := d.valueFromToml(mtype.Elem(), val)
			if err != nil {
				return mval, formatError(err, tval.GetPosition(key))
			}
			mval.SetMapIndex(reflect.ValueOf(key).Convert(mtype.Key()), mvalf)
		}
	}
	return mval, nil
}
func (d *Decoder) valueFromTreeSlice(mtype reflect.Type, tval []*Tree) (reflect.Value, error) {
	mval := reflect.MakeSlice(mtype, len(tval), len(tval))
	for i := 0; i < len(tval); i++ {
		val, err := d.valueFromTree(mtype.Elem(), tval[i])
		if err != nil {
			return mval, err
		}
		mval.Index(i).Set(val)
	}
	return mval, nil
}
func (d *Decoder) valueFromOtherSlice(mtype reflect.Type, tval []interface{}) (reflect.Value, error) {
	mval := reflect.MakeSlice(mtype, len(tval), len(tval))
	for i := 0; i < len(tval); i++ {
		val, err := d.valueFromToml(mtype.Elem(), tval[i])
		if err != nil {
			return mval, err
		}
		mval.Index(i).Set(val)
	}
	return mval, nil
}