dpstir0081 2017-08-24 16:12
浏览 44
已采纳

结构上的匿名函数

Is it possible to update a value on in a struct using an anonymous function? In python I would do the following with a lambda:

inspect = lambda id: '/api/{}/inspect'.format(id)

Which would place the dynamic id value in the string.

In Go I am trying something like his:

type Info struct {
    Inspect string
}

func Assign() Info  {
    i := &Info{}
    i.Inspect = return func(id) {return fmt.Sprintf("/api/%s/inspect", id)}
    return *i
}

But I want to update the value like this:

temp := Assign()
tempID := temp.Inspect("test")
fmt.Println("/api/test/inspect")
  • 写回答

2条回答 默认 最新

  • dongtang1910 2017-08-24 17:03
    关注

    Go is statically typed, where python is dynamically typed. This means that in Go, you must declare (or let the compiler infer) a type for each variable, and it must always stay that type. Therefore, you cannot assign your Inspect property (typed as a string) as a lambda function.

    Based on your question, it's not entirely clear how exactly you want this to work. Here is an example of what you could do, though:

    type Info struct {
        Inspect func(string) string
    }
    
    func Assign() Info  {
        i := Info{
            Inspect: func(id string) string { return fmt.Sprintf("/api/%s/inspect", id) },
        }
        return i
    }
    

    You can then use it like so:

    temp := Assign()
    tempID := temp.Inspect("test")
    fmt.Println(tempID)
    

    There is also no need to declare i as a pointer to Info and then return the value of it. Use one or the other.

    Here it is on the playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了