Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function declaration syntax in Go

What is (c App) in the following function declaration?

func (c App) SaveSettings(setting string) revel.Result {
--------------------------------------------------------------------------------------
func                                                      Keyword to define a function
     (c App)                                              ????
             SaveSettings                                 Function name
                         (setting string)                 Function arguments
                                          revel.Result    Return type
like image 691
Ivan Avatar asked Jul 23 '15 18:07

Ivan


People also ask

What does func () mean in Golang?

func: It is a keyword in Go language, which is used to create a function. function_name: It is the name of the function. Parameter-list: It contains the name and the type of the function parameters. Return_type: It is optional and it contain the types of the values that function returns.

What is () before function name in Golang?

The parenthesis before the function name is the Go way of defining the object on which these functions will operate. So, essentially ServeHTTP is a method of type handler and can be invoked using any object, say h, of type handler.

What is make () In Golang?

In Golang, make() is used for slices, maps, or channels. make() allocates memory on the heap and initializes and puts zero or empty strings into values. Unlike new() , make() returns the same type as its argument. Slice: The size determines the length.

How do functions work in Go?

A function in Go is also a type. If two function accepts the same parameters and returns the same values, then these two functions are of the same type. For example, add and substract which individually takes two integers of type int and return an integer of type int are of the same type.


1 Answers

(c App) gives the name and type of the receiver, Go's equivalent of C++ or JavaScript's this or Python's self. c is the receiver's name here, since in Go it's conventional to use a short, context-sensitive name instead of something generic like this. See http://golang.org/ref/spec#Method_declarations --

A method is a function with a receiver. The receiver is specified via an extra parameter section preceeding the method name.

and its example:

func (p *Point) Length() float64 {
    return math.Sqrt(p.x * p.x + p.y * p.y)
}
like image 133
twotwotwo Avatar answered Sep 21 '22 18:09

twotwotwo