doulu2011 2014-04-17 13:26
浏览 27
已采纳

为结构使用匿名方法

Does Go support anonymous methods for structures and if they do how do you create and call them?

This is the code I've been trying to get work but I'm unsure if Go(go version go1.1.2 linux/amd64) supports anonymous methods to structures.

package main

import (
  "fmt"
)

type Person struct{
  name string
  age int
}

func (p Person) get_details() string {
  return fmt.Sprintf("Name->%s, Age->%d", p.name, p.age)
}

func main() {
  p := Person{name:"G4143", age:5}

  //simple anonymous function which works
  fmt.Println(func(i int)int{return i * i}(34))

  str := p.get_details()

  fmt.Println(str)

  //anonymous method which won't compile
  str = p.func(p Person)()string{return fmt.Sprintf("Name->%s, Age->%d", p.name, p.age) }()

  fmt.Println(str)
}

I thank-you for any guidance..

  • 写回答

3条回答 默认 最新

  • dongxunhua2054 2014-04-17 13:33
    关注

    You can't do that, however you have 3 options :

    Private method :

    type Person struct{
        name string
        age int
    }
    
    func (p Person) Details() string { // public
        return fmt.Sprintf("Name->%s, Age->%d", p.name, p.age)
    }
    
    func (p Person) details() string { // private, notice the lowercase D
        return fmt.Sprintf("Name->%s, Age->%d", p.name, p.age)
    }
    

    Use the inline function just like this :

    str = func()string{return fmt.Sprintf("Name->%s, Age->%d", p.name, p.age) }()
    

    Pass the variable to the inline function :

    str = func(p Person) string { return fmt.Sprintf("Name->%s, Age->%d", p.name, p.age) }(p)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile