# 27. Methods

### Methods

In Go, methods are functions which are attached to a particular type. This gives functionality similar to Object Oriented Programming. Since methods are attached to particular type, we can reuse method name to attach them to different types.

### Declaring Methods

Method declaration is similar to function declaration, but in addition we need to provide the type to which this method is attached to. This type is called receiver.

`func (receiver type) name() { code to execute}`

First declaration below is a function `sayHello`, while second declaration is method `sayHello.`

{% code title="main.go" %}

```go
type user struct {
	name string
}

func sayHello(u user) {
	fmt.Printf("Hello, %s from function \n", u.name)
}

func (u user) sayHello() {
	fmt.Printf("Hello, %s from method\n", u.name)
}

func main() {
	u := user{
		name: "Gopher",
	}
	// function call
	sayHello(u)
	// method call
	u.sayHello()
}
```

{% endcode %}

### Pointer Receiver

We use pointer to share data to avoid unnecessary copy operation on data. Similarly, pointer receivers are used so that method can operate directly operate on data without making copy operation. We are passing pointer to user and `updateUser` method updates the same value. that we have created in `main` function.

{% code title="main.go" %}

```go
func (u *user) updateUser() {
	u.name = "Bob"
}

func main() {
	u := &user{
		name: "Gopher",
	}
	u.updateUser()
	fmt.Println(u.name)
}

```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://book.codewithgo.com/methods.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
