# Functional Options Pattern

* when you want to provide optional configuration

From:

{% code lineNumbers="true" %}

```go
type Server struct{
    host string
    port int
    protocol string
}

func NewServer(host string, port int) *Server{
    return &Server{
        host: host,
        port: port,
        protocol: "http",
    }
}
```

{% endcode %}

To:

{% code lineNumbers="true" %}

```go
type ServerOption func(*Server)

func WithPort(port int) ServerOption{
    return func(s *Server){
        s.port = port
    }
}

func NewServer(host string, opts ...ServerOption) *Server{
    server := &Server{
        host: host,
        port: 443,
        protocol: "http",
    }
    
    for _, opt := range = opts{
        opt(server)
    }
    
    return server
}

server1 := NewServer("localhost")  
server2 := NewServer("localhost", WithPort(8080))
```

{% 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://dianadarie.gitbook.io/go-guide/principles-and-patterns/functional-options-pattern.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.
