我有一个带有切片字段的.cc-selector{
position: relative;
left: 600px;
top: 250;
}
.cc-selector input{
margin:0;padding:0;
-webkit-appearance:none;
-moz-appearance:none;
appearance:none;
}
.visa{background-image:url(http://i.imgur.com/lXzJ1eB.png);}
.mastercard{background-image:url(http://i.imgur.com/SJbRQF7.png);}
.cc-selector input:active +.drinkcard-cc{opacity: .9;}
.cc-selector input:checked +.drinkcard-cc{
-webkit-filter: none;
-moz-filter: none;
filter: none;
}
.drinkcard-cc{
cursor:pointer;
background-size:contain;
background-repeat:no-repeat;
display:inline-block;
width:100px;height:70px;
-webkit-transition: all 100ms ease-in;
-moz-transition: all 100ms ease-in;
transition: all 100ms ease-in;
-webkit-filter: brightness(1.8) grayscale(1) opacity(.7);
-moz-filter: brightness(1.8) grayscale(1) opacity(.7);
filter: brightness(1.8) grayscale(1) opacity(.7);
}
.drinkcard-cc:hover{
-webkit-filter: brightness(1.2) grayscale(.5) opacity(.9);
-moz-filter: brightness(1.2) grayscale(.5) opacity(.9);
filter: brightness(1.2) grayscale(.5) opacity(.9);
}
结构:
Favorites
我有type Favorites struct {
Color string
Lunch string
Place string
Hobbies []string
}
,其中包含其他结构:
Person
我想看看是否在Person上设置了type Person struct {
Name string
Favorites Favorites
}
字段。对于其他类型的字段,例如字符串或int,我会将该字段与零值(分别为“”或0)进行比较。
如果我尝试与下面的零进行比较,我会收到错误Favorites
:
invalid operation: p2.Favorites == zeroValue (struct containing []string cannot be compared)
这符合规范(https://golang.org/ref/spec#Comparison_operators)中定义的内容。
除了繁琐地比较每个字段(并且如果结构发生变化时必须记住更新它)之外,还有其他方法可以进行这种比较吗?
一个选项是使“收藏夹”字段成为指向结构而不是结构本身的指针,然后只与nil进行比较,但这是在一个大型代码库中,所以我宁愿不在这种情况下做出可能影响深远的更改
答案 0 :(得分:3)
According to this,您可以使用reflect.DeepEqual()
,但可能应该自己编写:
type Favorites struct {
Color string
Lunch string
Place string
Hobbies []string
}
func (favs *Favorites) Equals(other *Favorites) bool {
color_eq := favs.Color == other.Color
lunch_eq := favs.Lunch == other.Lunch
place_eq := favs.Place == other.Place
hobbies_eq := len(favs.Hobbies) == len(other.Hobbies)
if hobbies_eq { // copy slices so sorting won't affect original structs
f_hobbies := make([]string, len(favs.Hobbies))
o_hobbies := make([]string, len(other.Hobbies))
copy(favs.Hobbies, f_hobbies)
copy(other.Hobbies, o_hobbies)
sort.Strings(f_hobbies)
sort.Strings(o_hobbies)
for index, item := range f_hobbies {
if item != o_hobbies[index] {
hobbies_eq = false
}
}
}
return (color_eq && lunch_eq && place_eq && hobbies_eq)
}
然后用:
调用它p2.Favorites.Equals(zeroValue)