无法将 nil 转换为类型 x。

huangapple go评论83阅读模式
英文:

Cannot convert nil to type x

问题

考虑以下示例:

    lock.RLock()
var product *Product
if store[productId] != nil {     //无法将nil转换为Product类型
    product = &Product{}
    *product = *store[productId] //store[productId]的间接引用无效(类型为Product)
}
lock.RUnlock()

每行的注释表示异常,我真的不明白我做错了什么。。

store 是一个 map[int]Product

有什么想法吗?

英文:

Consider the following example:

    lock.RLock()
	var product *Product
	if store[productId] != nil {     //cannot convert nil to type Product
		product = &Product{}
		*product = *store[productId] //invalid indirect of store[productId] (type Product)
	}
	lock.RUnlock()

The exceptions are as commented per line and i don't really get what i am doing wrong..

store is a map[int]Product

any ideas?

答案1

得分: 6

你正在将store用作已声明的方式:

store := make(map[int]*Product)
英文:

You are using store as if it were declared as:

store := make(map[int]*Product)

huangapple
  • 本文由 发表于 2014年7月13日 11:15:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/24719221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定