Go function with parameters

Asked

Viewed 306 times

1

I came across the following function in a framework of Map Reduce, but I didn’t understand her syntax.

func (fc *FlowContext) newNextDataset(shardSize int, dType reflect.Type) (ret *Dataset) {
    ret = NewDataset(fc, dType)
    if dType != nil {
        ret.SetupShard(shardSize)
    }
    return
}

Because we have three parentheses?

2 answers

4


The first pair is used to receive a parameter that is treated in a special way. This is called method receiver. It is a very similar way as languages treat methods where there is an implicit parameter that is the object this, but in the case of Go is received explicitly. Being separated it is easier for the compiler to identify the special condition. Thus the method is applied only to a specific type. This way you can call the function as a method, that is, you call the method according to the object in use. If you think about it it makes even more sense than in other languages because you treat in the definition the parameter that is special and in the place that it is used in the call, although the syntax gets a little weird.

The second pair is used to establish a tuple of parameters, equal to all languages.

The third pair is used to group the return type of the function that always comes after the name and parameters of the function. It is used because in the case the type consists of a pointer and has the parameter name, thus avoids ambiguity and ensures that it is one thing.

  • A tip for those who know C# and VB: That syntax is like a Extension method for the guy FlowContext, then you can call flowContext.newNextDataSet(p1, p2) instead of newNextDataSet(flowContext, p1, p2).

  • Yeah, it’s good looking.

1

When I studied this syntax, to fix it, I understood that they were methods related to a certain object. In this example we use the Flowcontext struct. After instantiating this class in an object it will be possible to call this method directly.

So let’s go to the example:

var obj FlowContext

//Veja que chamo o método através do próprio objeto declarado acima.
objDataSet := obj.newNextDataset(1, dType)

There is an excerpt in the documentation that explains this type of syntax ;) https://tour.golang.org/methods/3

But it became clearer to you?

[]'s

Browser other questions tagged

You are not signed in. Login or sign up in order to post.