英文:
golang type assertion, what the different between interface{}(pointer) and interface{}(object)?
问题
为什么在将接口分配给指针时,对类型断言结果进行赋值是可以的,但是对分配给结构体对象的接口进行赋值时会出现“无法分配”的错误?
这是我的代码:
package main
import (
"fmt"
)
type Person interface {
SayHi()
}
type Student struct {
id int
name string
}
func (s Student) SayHi() {
fmt.Println("hi, i am", s.name, "my id is:", s.id)
}
func main() {
p1 := Person(&Student{id: 123, name: "William"})
p1.SayHi() // 正常
p1.(*Student).SayHi() // 正常
p1.(*Student).id = 456 // 正常
p2 := Person(Student{id: 123, name: "William"})
p2.SayHi() // 正常
p2.(Student).SayHi() // 正常
p2.(Student).id = 456 // 出现错误,为什么?
fmt.Println("p1:", p1, "p2:", p2)
}
链接: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:
package main
import (
"fmt"
)
type Person interface {
SayHi()
}
type Student struct {
id int
name string
}
func (s Student) SayHi() {
fmt.Println("hi, i am", s.name, " my id is:", s.id)
}
func main() {
p1 := Person(&Student{id: 123, name: "William"})
p1.SayHi() // ok
p1.(*Student).SayHi() // ok here
p1.(*Student).id = 456 // ok here
p2 := Person(Student{id: 123, name: "William"})
p2.SayHi() //ok
p2.(Student).SayHi() // ok here
p2.(Student).id = 456 // error here and why?
fmt.Println("p1:", p1, " p2:", p2)
}
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论