go语言中的map和struct都能表示key/value,使用时怎么确定用map还是struct?
我认为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.
而Values
在url
包中是储存表单的,使用者会存入什么样的kv数据是设计者不知道的,所以这里必然是使用map.
很多时候大家喜欢定义一个结构体来解析已知结构的json,也有很多人喜欢把json解析到map[string]interface{},我个人认为结构体的可读性是更强一点的,但是不够灵活,而map虽然足够灵活,但是在可读性上差一点,二者都可以使用的情况下,用结构体我觉得更好一点.
map和struct的功能并不是相同的。
所以,如果需要kv,优先使用kv,并发场景下考虑使用sync.Map。
7 回答5.3k 阅读
6 回答6.8k 阅读✓ 已解决
4 回答2.3k 阅读
1 回答3.4k 阅读
2 回答2.2k 阅读
1 回答2.1k 阅读
1 回答1.5k 阅读
知道接收到的数据结构, 并且能将它抽象出来的时候就用
struct
不知道具体会/临时存放/或者暂时不知道怎么处理他, 就用
map