package main
type Data struct{}
func (Data) TestValue() {}
func (*Data) TestPointer() {}
func main() { var p *Data = nil p.TestPointer()
(*Data)(nil).TestPointer() // method value
(*Data).TestPointer(nil) // method expression
// p.TestValue() // invalid memory address or nil pointer dereference
// (Data)(nil).TestValue() // cannot convert nil to type Data
// Data.TestValue(nil) // cannot use nil as type Data in function argument
}
为什么能这么用? (Data)(nil).TestPointer() , 第一个Data 我不懂, 我知道强制类型转换是 T(), 就相当于只有*Data(nil), 但是为啥又多套了一个(), 啥原理啊, 抱歉实在不知道怎么谷歌, go 小白
1
XiaoXiaoMagician 1 天前
这种情况建议把如何使用 AI 纳入学习
|
2
GeruzoniAnsasu 1 天前
|
![]() |
3
PTLin 1 天前
nil 是没有类型的,(XXX*)(nil)让这个 nil 赋予了特定类型,这不是很常见的用法吗,c 里就是这么搞的。
|
4
960930marui OP @GeruzoniAnsasu 感谢 问题解决了
|