英文:
Struct type immtable
问题
我写了一个关于给变量赋值的示例应用程序。请看下面的代码片段:
package main
import (
"fmt"
)
func main() {
cp := 344
fmt.Println(cp)
cp = 566565
fmt.Println(cp)
res := []struct {
Email string `json:"n.email"`
Activated bool `json:"n.activated"`
}{}
fmt.Println(res)
res = []struct {
Email string `json:"n.email"`
}{}
fmt.Println(res)
}
第一个变量 cp
,我先赋值,然后再次赋值,它可以正常工作。最后,cp
的值为 566565。对我来说,int
是可变的。
第二段代码不起作用,我尝试将新的结构体重新赋值给 res
,但是我得到了编译器错误。
./double_assignment.go:23: cannot use []struct { Email string }
literal (type []struct { Email string }) as type []struct { Email
string; Activated bool } in assignment
结构体是不可变的吗?
英文:
I wrote a sample application about assign value to variable. Look at the following code snippet:
package main
import (
"fmt"
)
func main() {
cp := 344
fmt.Println(cp)
cp = 566565
fmt.Println(cp)
res := []struct {
Email string `json:"n.email"`
Activated bool `json:"n.activated"`
}{}
fmt.Println(res)
res = []struct {
Email string `json:"n.email"`
}{}
fmt.Println(res)
}
First cp variable, I assign value then after do it again and it works. At the end cp carry the value 566565. For me is int mutable.
The second code does not work, reassign new struct to res, I got compiler error.
> ./double_assignment.go:23: cannot use []struct { Email string }
> literal (type []struct { Email string }) as type []struct { Email
> string; Activated bool } in assignment
Is struct immutable?
答案1
得分: 2
第一个短变量声明 res :=
设置了一个特定类型 ([]struct { Email string; Activated bool}
)。
如果你想分配一个不同的类型(在这里,一个不同的 struct
字面量 []struct { Email string }
),你需要一个不同的变量。
res2 = []struct {
Email string `json:"n.email"`
}{}
fmt.Println(res2)
(参考 play.golang.org )
英文:
The first short variable declaration res :=
did set a certain type ([]struct { Email string; Activated bool}
).
If you want to assign a different type (here, a different struct
literal []struct { Email string }
), you need a different variable.
res2 = []struct {
Email string `json:"n.email"`
}{}
fmt.Println(res2)
(as in play.golang.org )
答案2
得分: 2
不,你的类型不兼容。res
的类型是
[]struct {
Email string
Activated bool
}
但你试图给它一个
[]struct {
Email string
// 注意没有 Activated 字段!
}
切片的元素类型是类型的一部分;即使某些字段似乎是共享的,你也不能混合使用。
英文:
No, your types are incompatible. The type of res
is
[]struct {
Email string
Activated bool
}
but you are trying to give it a
[]struct {
Email string
// notice no Activated!
}
The element type of a slice is part of the type; you can't mix and match like this, even if some fields seem to be shared.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论