Skip to content

第一册P257页的示例代码的疑惑 #38

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Laevon opened this issue Sep 9, 2024 · 2 comments
Closed

第一册P257页的示例代码的疑惑 #38

Laevon opened this issue Sep 9, 2024 · 2 comments

Comments

@Laevon
Copy link

Laevon commented Sep 9, 2024

2023年10月版本,示例:

type T int

func (t T) Error() string {
	return "bad error"
}

func main() {
	var eif interface{} = T(5)
	var err error = T(5)
	println("eif:", eif)
	println("err:", err)
	println("eif = err:", eif == err)

	dumpEface(eif)
	dumpItabOfIface(unsafe.Pointer(&err))
	dumpDataOfIface(err)
}

为什么在调用dumpEface(eif)后,eif的data值为bad error而不是5呢,空接口赋值为T类型值5时,也会隐式调用Error方法吗?

@bigwhite
Copy link
Owner

bigwhite commented Sep 9, 2024

看本仓库的chapter5/sources/dumpinterface.go。这里面dumpEface会判断i.type,如果是T类型,则调用dumpT,而后者实现如下:

func dumpT(dataOfIface unsafe.Pointer) {
    var p *T = (*T)(dataOfIface)
    fmt.Printf("\t data: %+v\n", *p)
}

是这里的Printf会调用T的Error函数返回bad error。

@Laevon
Copy link
Author

Laevon commented Sep 9, 2024

看本仓库的chapter5/sources/dumpinterface.go。这里面dumpEface会判断i.type,如果是T类型,则调用dumpT,而后者实现如下:

func dumpT(dataOfIface unsafe.Pointer) {
    var p *T = (*T)(dataOfIface)
    fmt.Printf("\t data: %+v\n", *p)
}

是这里的Printf会调用T的Error函数返回bad error。

谢谢您如此及时的回复!

@Laevon Laevon closed this as completed Sep 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants