go文档模式,编译出错,各位道友帮忙看看

meijies · 2017-10-30 12:43:51 · 1376 次点击
github.com/meijies/theme/collection/config
./document.go:21:29: cannot assign to struct field target.sub[subkey].value in map
./document.go:23:11: cannot use target.sub[subkey] (type doc) as type *doc in assignment
./document.go:33:10: cannot use target.sub[subkey] (type doc) as type *doc in assignment
FAIL    command-line-arguments [build failed]
#5
更多评论
package config

import "strings"

type doc struct {
    value string
    sub   map[string]doc
}

var root = new(doc)

func Add(key string, value string) {
    keys := strings.Split(key, ".")
    var target = root
    for index, subkey := range keys {
        if target.sub == nil {
            target.sub = make(map[string]doc)
            target.sub[subkey] = doc{}
        }
        if index == len(keys)-1 {
            target.sub[subkey].value = value
        } else {
            target = target.sub[subkey]
        }
    }

}

func Get(key string) string {
    keys := strings.Split(key, ".")
    target := root
    for index, subkey := range keys {
        target = target.sub[subkey]
        if index == len(keys)-1 {
            return target.value
        }
    }
    return ""
}
#1