go语言中的map和struct都能表示key/value,使用时怎么确定用哪个?

go语言中的map和struct都能表示key/value,使用时怎么确定用map还是struct?

阅读 8.7k
5 个回答

知道接收到的数据结构, 并且能将它抽象出来的时候就用 struct
不知道具体会/临时存放/或者暂时不知道怎么处理他, 就用 map

我认为struct并不是为了单纯储存KV数据结构而设计出来的.
参考一些开源框架和内置模块,struct定义的数据结构一般都是比较复杂的数据结构.对比一下两个比较典型的用法,
以下代码来自url


// A URL represents a parsed URL (technically, a URI reference).
//
// The general form represented is:
//
//    [scheme:][//[userinfo@]host][/]path[?query][#fragment]
//
// URLs that do not start with a slash after the scheme are interpreted as:
//
//    scheme:opaque[?query][#fragment]
//
// Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/.
// A consequence is that it is impossible to tell which slashes in the Path were
// slashes in the raw URL and which were %2f. This distinction is rarely important,
// but when it is, code must not use Path directly.
// The Parse function sets both Path and RawPath in the URL it returns,
// and URL's String method uses RawPath if it is a valid encoding of Path,
// by calling the EscapedPath method.
type URL struct {
    Scheme     string
    Opaque     string    // encoded opaque data
    User       *Userinfo // username and password information
    Host       string    // host or host:port
    Path       string    // path (relative paths may omit leading slash)
    RawPath    string    // encoded path hint (see EscapedPath method)
    ForceQuery bool      // append a query ('?') even if RawQuery is empty
    RawQuery   string    // encoded query values, without '?'
    Fragment   string    // fragment for references, without '#'
}

// Values maps a string key to a list of values.
// It is typically used for query parameters and form values.
// Unlike in the http.Header map, the keys in a Values map
// are case-sensitive.
type Values map[string][]string

可以看出来,URL这个结构体,这里将会出现什么属性是我们已知的,相对可控的,一定程度上可以对标其他语言的class.
Valuesurl包中是储存表单的,使用者会存入什么样的kv数据是设计者不知道的,所以这里必然是使用map.

很多时候大家喜欢定义一个结构体来解析已知结构的json,也有很多人喜欢把json解析到map[string]interface{},我个人认为结构体的可读性是更强一点的,但是不够灵活,而map虽然足够灵活,但是在可读性上差一点,二者都可以使用的情况下,用结构体我觉得更好一点.

struct,就是你知道key有哪些和对应的数据类型
map,就是你不能确定key有哪些

map和struct的功能并不是相同的。

  • map用来形成一对一的映射关系,目的在快速查找数据。
  • struct用来把多个数据组合成一个数据体,以组合体的方式,用数据表示真实的对象。

所以,如果需要kv,优先使用kv,并发场景下考虑使用sync.Map。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题