简体   繁体   English

struct上的匿名函数

[英]Anonymous function on struct

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: 在python中,我将使用lambda执行以下操作:

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

Which would place the dynamic id value in the string. 哪个会将动态id值放在字符串中。

In Go I am trying something like his: 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
}

But I want to update the value like this: 但我想更新这样的值:

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

Go is statically typed, where python is dynamically typed. Go是静态类型的,其中python是动态类型的。 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. 这意味着在Go中,您必须声明(或让编译器推断)每个变量的类型,并且它必须始终保持该类型。 Therefore, you cannot assign your Inspect property (typed as a string ) as a lambda function. 因此,您不能将Inspect属性(键入为string )指定为lambda函数。

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. 也没有必要将i声明为指向Info的指针,然后返回它的值。 Use one or the other. 使用其中一个。

Here it is on the playground. 是在操场上。

You can certainly define an anonymous function as a property of a struct, but the type has to be the full function signature, rather than just the return value of the function. 您当然可以将匿名函数定义为结构的属性,但类型必须是完整的函数签名,而不仅仅是函数的返回值。

type Info struct {
    Inspect func(string) string
}

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


func main() {
    temp := Assign()
    tempID := temp.Inspect("test")
    fmt.Println(tempID)
}

Feel free to play around with that here: https://play.golang.org/p/IRylodv2cZ 请随意玩这个: https//play.golang.org/p/IRylodv2cZ

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM