Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous function on struct

Tags:

go

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")
like image 902
ChaChaPoly Avatar asked Aug 24 '17 16:08

ChaChaPoly


People also ask

What is anonymous fields in Go struct?

Posted on June 14, 2020. A struct can have anonymous fields as well, meaning a field having no name. The type will become the field name. In below example, string will be the field name as well type employee struct { string age int salary int }

Can anonymous functions be stored in variables?

An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle . Anonymous functions can accept multiple inputs and return one output.

What is anonymous function with example?

An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation. Normal function definition: function hello() { alert('Hello world'); } hello();

Is an anonymous function a closure?

Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.


1 Answers

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.

like image 164
Gavin Avatar answered Oct 07 '22 01:10

Gavin