英文:
Ccheck if struct exists
问题
我正在遍历一个type company struct
的切片,每个公司内部都有一个type image struct
,所以当我遍历公司切片时,我有一个if语句,我想检查company.Image
是否为nil,但是我收到以下错误Cannot convert 'nil' to type 'Image'
。我的简化代码如下,有人能提供一个简单的解决方案吗?
type Company struct {
Name string `json:"name" bson:"name,omitempty"`
Image Image `json:"image" bson:"image,omitempty"`
}
type Image struct {
ID string `json:"id" bson:"id,omitempty"`
Name string `json:"name" bson:"name,omitempty"`
}
func checkCompanyCredibility(companies []Company) int {
rating := 0
for _, company := range companies {
if company.Image != nil {
rating += 3
break
}
}
return rating
}
英文:
I am looping through a slice of type company struct
and inside every company there is a type image struct
so when I loop through the company slice I have an if statement where I want to check if the company.Image
is nil or not, but I receive the following error Cannot convert 'nil' to type 'Image'
. My simplified code is below could anyone suggest a simple solution for this?
type Company struct {
Name string `json:"name" bson:"name,omitempty"`
Image Image `json:"image" bson:"image,omitempty"`
}
type Image struct {
ID string `json:"id" bson:"id,omitempty"`
Name string `json:"name" bson:"name,omitempty"`
}
func checkCompanyCredibility(companies []Company) int{
rating := 0
for _, company := range companies{
if company.Image != nil {
rating =+ 3
break
}
}
return rating
}
答案1
得分: 1
你只需要将以下代码进行替换:
Image Image `json:"image" bson:"image,omitempty"`
替换为:
Image *Image `json:"image" bson:"image,omitempty"`
这样,company.Image
将会是一个指针类型,你可以检查它是否为 nil
。
英文:
You need just to replace:
Image Image `json:"image" bson:"image,omitempty"`
To:
Image *Image `json:"image" bson:"image,omitempty"`
In this case company.Image
will be pointer and you can check whether it's nil
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论