V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
960930marui
V2EX  ›  Go 编程语言

这几个圆括号给我看蒙圈了,没明白啥意思

  •  1
     
  •   960930marui · 1 天前 · 991 次点击

    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 小白

    4 条回复    2025-03-12 11:49:10 +08:00
    XiaoXiaoMagician
        1
    XiaoXiaoMagician  
       1 天前
    这种情况建议把如何使用 AI 纳入学习
    GeruzoniAnsasu
        2
    GeruzoniAnsasu  
       1 天前
    复制粘贴 AI 的回答会引爆账号,所以

    > claude.ai:
    > 我对 golang 的语法感到疑惑,帮我逐字逐句分析一下 demo 里的各个表达式是什么意思,怎么构成的

    自己看
    PTLin
        3
    PTLin  
       1 天前
    nil 是没有类型的,(XXX*)(nil)让这个 nil 赋予了特定类型,这不是很常见的用法吗,c 里就是这么搞的。
    960930marui
        4
    960930marui  
    OP
       1 天前
    @GeruzoniAnsasu 感谢 问题解决了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5214 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 09:15 · PVG 17:15 · LAX 02:15 · JFK 05:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.