是否可以使用匿名函数更新结构中的值?在python中,我将使用lambda执行以下操作:
inspect = lambda id: '/api/{}/inspect'.format(id)
Run Code Online (Sandbox Code Playgroud)
哪个会将动态id值放在字符串中.
在Go我尝试像他这样的东西:
type Info struct {
Inspect string
}
func Assign() Info {
i := &Info{}
i.Inspect = return func(id) {return fmt.Sprintf("/api/%s/inspect", id)}
return *i
}
Run Code Online (Sandbox Code Playgroud)
但我想更新这样的值:
temp := Assign()
tempID := temp.Inspect("test")
fmt.Println("/api/test/inspect")
Run Code Online (Sandbox Code Playgroud)
Go是静态类型的,而python是动态类型的。这意味着在Go中,您必须为每个变量声明(或让编译器推断)类型,并且它必须始终保持该类型。因此,您不能将Inspect属性(键入为string)分配为lambda函数。
根据您的问题,尚不清楚您希望它如何工作。不过,这是您可以做什么的示例:
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
}
Run Code Online (Sandbox Code Playgroud)
然后可以像这样使用它:
temp := Assign()
tempID := temp.Inspect("test")
fmt.Println(tempID)
Run Code Online (Sandbox Code Playgroud)
也无需声明i为指针Info,然后返回它的值。使用一个或另一个。
这是在操场上。
| 归档时间: |
|
| 查看次数: |
2689 次 |
| 最近记录: |