The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
Kremlin

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

  •  1
     
  •   Kremlin · Mar 12, 2025 · 2479 views
    This topic created in 429 days ago, the information mentioned may be changed or developed.

    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 replies    2025-03-12 11:49:10 +08:00
    XiaoXiaoMagician
        1
    XiaoXiaoMagician  
       Mar 12, 2025
    这种情况建议把如何使用 AI 纳入学习
    GeruzoniAnsasu
        2
    GeruzoniAnsasu  
       Mar 12, 2025
    复制粘贴 AI 的回答会引爆账号,所以

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

    自己看
    PTLin
        3
    PTLin  
       Mar 12, 2025
    nil 是没有类型的,(XXX*)(nil)让这个 nil 赋予了特定类型,这不是很常见的用法吗,c 里就是这么搞的。
    Kremlin
        4
    Kremlin  
    OP
       Mar 12, 2025
    @GeruzoniAnsasu 感谢 问题解决了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5461 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 09:15 · PVG 17:15 · LAX 02:15 · JFK 05:15
    ♥ Do have faith in what you're doing.