golang类型断言,interface{}(指针)和interface{}(对象)之间有什么区别?

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

golang type assertion, what the different between interface{}(pointer) and interface{}(object)?

问题

为什么在将接口分配给指针时,对类型断言结果进行赋值是可以的,但是对分配给结构体对象的接口进行赋值时会出现“无法分配”的错误?

这是我的代码:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Person interface {
  6. SayHi()
  7. }
  8. type Student struct {
  9. id int
  10. name string
  11. }
  12. func (s Student) SayHi() {
  13. fmt.Println("hi, i am", s.name, "my id is:", s.id)
  14. }
  15. func main() {
  16. p1 := Person(&Student{id: 123, name: "William"})
  17. p1.SayHi() // 正常
  18. p1.(*Student).SayHi() // 正常
  19. p1.(*Student).id = 456 // 正常
  20. p2 := Person(Student{id: 123, name: "William"})
  21. p2.SayHi() // 正常
  22. p2.(Student).SayHi() // 正常
  23. p2.(Student).id = 456 // 出现错误,为什么?
  24. fmt.Println("p1:", p1, "p2:", p2)
  25. }

链接:https://play.golang.org/p/dwkvLzng_n

英文:

Why do I assign a value to a type assertion result where the interface is assigned by a pointer, and it comes to a "cannot assign" error when I do it to a interface which is assigned by a struct object?

Here's my code:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Person interface {
  6. SayHi()
  7. }
  8. type Student struct {
  9. id int
  10. name string
  11. }
  12. func (s Student) SayHi() {
  13. fmt.Println("hi, i am", s.name, " my id is:", s.id)
  14. }
  15. func main() {
  16. p1 := Person(&Student{id: 123, name: "William"})
  17. p1.SayHi() // ok
  18. p1.(*Student).SayHi() // ok here
  19. p1.(*Student).id = 456 // ok here
  20. p2 := Person(Student{id: 123, name: "William"})
  21. p2.SayHi() //ok
  22. p2.(Student).SayHi() // ok here
  23. p2.(Student).id = 456 // error here and why?
  24. fmt.Println("p1:", p1, " p2:", p2)
  25. }

https://play.golang.org/p/dwkvLzng_n

答案1

得分: 5

value.(typeName) 的结果是一个具有静态类型 typeName 的新值(副本)。

p2.(Student).id=456 将创建一个临时的 Student 值,对该值的任何修改都将被丢弃。因此,语言只是禁止了这个错误。

英文:

the result of value.(typeName) is a new (copy) value with the static type typeName.

p2.(Student).id=456 will create a temporary Student value, any modifications of that value would be discarded. So the language just disallows this mistake.

huangapple
  • 本文由 发表于 2017年3月10日 16:12:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/42713395.html
匿名

发表评论

匿名网友

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

确定