检查结构体是否存在

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

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.

huangapple
  • 本文由 发表于 2021年8月19日 00:02:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/68835740.html
匿名

发表评论

匿名网友

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

确定