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

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

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)
}

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:

确定