Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do the brackets after func mean in Go?

Tags:

go

As a Go beginner, I stumbled across code where there are brackets directly after func

func (v Version) MarshalJSON() ([]byte, error) {
  return json.Marshal(v.String())
}

So what does (v Version) mean?

like image 800
pogopaule Avatar asked Sep 02 '15 19:09

pogopaule


People also ask

What do the brackets after a function do?

In JavaScript, the functions wrapped with parenthesis are called “Immediately Invoked Function Expressions" or "Self Executing Functions. The purpose of wrapping is to namespace and control the visibility of member functions. It wraps code inside a function scope and decrease clashing with other libraries.

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.

Why do functions have parentheses?

Parentheses have multiple functions relating to functions and structures. They are used to contain a list of parameters passed to functions and control structures and they are used to group expressions to control the order of execution.

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

This is not a function but a method. In this case, it adds the MarshalJSON method to the Version struct type.

The v is the name for the received value (and would be analogous to this in a Java method or self in Python), the Version specifies the type we're adding the method to.

See go by example for, well, an example, and the specification for more details.

like image 50
Wander Nauta Avatar answered Oct 17 '22 09:10

Wander Nauta