Telegram Group & Telegram Channel
⚙️ Option Pattern в Go: гибкая и читаемая настройка объектов

В статье Leapcell ["Option Pattern in Go: Advanced Parameter Handling"](https://dev.to/leapcell/option-pattern-in-go-advanced-parameter-handling-15hf) рассматривается эффективный способ управления параметрами функций и конструкторов в Go.:contentReference[oaicite:7]{index=7}

## 🧩 Проблема

:contentReference[oaicite:9]{index=9}:contentReference[oaicite:11]{index=11}


func NewServer(addr string, port int, timeout time.Duration, maxConn int, protocol string) *Server {
// ...
}


Недостатки:
- :contentReference[oaicite:13]{index=13}
- :contentReference[oaicite:16]{index=16}
- :contentReference[oaicite:19]{index=19}
- :contentReference[oaicite:22]{index=22}:contentReference[oaicite:24]{index=24}

## 💡 Решение: Option Pattern

:contentReference[oaicite:26]{index=26}:contentReference[oaicite:28]{index=28}


type Server struct {
addr string
port int
timeout time.Duration
maxConn int
protocol string
}

type Option func(*Server)

func WithTimeout(t time.Duration) Option {
return func(s *Server) {
s.timeout = t
}
}

func WithMaxConn(max int) Option {
return func(s *Server) {
s.maxConn = max
}
}



:contentReference[oaicite:30]{index=30}:contentReference[oaicite:32]{index=32}


func NewServer(addr string, opts ...Option) *Server {
s := &Server{
addr: addr,
port: 8080,
timeout: 30 * time.Second,
maxConn: 100,
protocol: "tcp",
}

for _, opt := range opts {
opt(s)
}
return s
}


Использование:


server := NewServer("localhost",
WithTimeout(60*time.Second),
WithMaxConn(500),
)


## 🛠️ Дополнительные возможности

- Валидация параметров:


func WithPort(port int) Option {
return func(s *Server) {
if port < 0 || port > 65535 {
panic("invalid port number")
}
s.port = port
}
}


- Группировка опций:


type NetworkOptions struct {
Protocol string
Timeout time.Duration
}

func WithNetworkOptions(opts NetworkOptions) Option {
return func(s *Server) {
s.protocol = opts.Protocol
s.timeout = opts.Timeout
}
}


Преимущества

- :contentReference[oaicite:34]{index=34}
- :contentReference[oaicite:37]{index=37}
- :contentReference[oaicite:40]{index=40}
- :contentReference[oaicite:43]{index=43}:contentReference[oaicite:45]{index=45}

:contentReference[oaicite:47]{index=47}:contentReference[oaicite:49]{index=49}

📌 Читать



tg-me.com/golang_interview/1192
Create:
Last Update:

⚙️ Option Pattern в Go: гибкая и читаемая настройка объектов

В статье Leapcell ["Option Pattern in Go: Advanced Parameter Handling"](https://dev.to/leapcell/option-pattern-in-go-advanced-parameter-handling-15hf) рассматривается эффективный способ управления параметрами функций и конструкторов в Go.:contentReference[oaicite:7]{index=7}

## 🧩 Проблема

:contentReference[oaicite:9]{index=9}:contentReference[oaicite:11]{index=11}


func NewServer(addr string, port int, timeout time.Duration, maxConn int, protocol string) *Server {
// ...
}


Недостатки:
- :contentReference[oaicite:13]{index=13}
- :contentReference[oaicite:16]{index=16}
- :contentReference[oaicite:19]{index=19}
- :contentReference[oaicite:22]{index=22}:contentReference[oaicite:24]{index=24}

## 💡 Решение: Option Pattern

:contentReference[oaicite:26]{index=26}:contentReference[oaicite:28]{index=28}


type Server struct {
addr string
port int
timeout time.Duration
maxConn int
protocol string
}

type Option func(*Server)

func WithTimeout(t time.Duration) Option {
return func(s *Server) {
s.timeout = t
}
}

func WithMaxConn(max int) Option {
return func(s *Server) {
s.maxConn = max
}
}



:contentReference[oaicite:30]{index=30}:contentReference[oaicite:32]{index=32}


func NewServer(addr string, opts ...Option) *Server {
s := &Server{
addr: addr,
port: 8080,
timeout: 30 * time.Second,
maxConn: 100,
protocol: "tcp",
}

for _, opt := range opts {
opt(s)
}
return s
}


Использование:


server := NewServer("localhost",
WithTimeout(60*time.Second),
WithMaxConn(500),
)


## 🛠️ Дополнительные возможности

- Валидация параметров:


func WithPort(port int) Option {
return func(s *Server) {
if port < 0 || port > 65535 {
panic("invalid port number")
}
s.port = port
}
}


- Группировка опций:


type NetworkOptions struct {
Protocol string
Timeout time.Duration
}

func WithNetworkOptions(opts NetworkOptions) Option {
return func(s *Server) {
s.protocol = opts.Protocol
s.timeout = opts.Timeout
}
}


Преимущества

- :contentReference[oaicite:34]{index=34}
- :contentReference[oaicite:37]{index=37}
- :contentReference[oaicite:40]{index=40}
- :contentReference[oaicite:43]{index=43}:contentReference[oaicite:45]{index=45}

:contentReference[oaicite:47]{index=47}:contentReference[oaicite:49]{index=49}

📌 Читать

BY Golang вопросы собеседований


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/golang_interview/1192

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

Can I mute a Telegram group?

In recent times, Telegram has gained a lot of popularity because of the controversy over WhatsApp’s new privacy policy. In January 2021, Telegram was the most downloaded app worldwide and crossed 500 million monthly active users. And with so many active users on the app, people might get messages in bulk from a group or a channel that can be a little irritating. So to get rid of the same, you can mute groups, chats, and channels on Telegram just like WhatsApp. You can mute notifications for one hour, eight hours, or two days, or you can disable notifications forever.

Should You Buy Bitcoin?

In general, many financial experts support their clients’ desire to buy cryptocurrency, but they don’t recommend it unless clients express interest. “The biggest concern for us is if someone wants to invest in crypto and the investment they choose doesn’t do well, and then all of a sudden they can’t send their kids to college,” says Ian Harvey, a certified financial planner (CFP) in New York City. “Then it wasn’t worth the risk.” The speculative nature of cryptocurrency leads some planners to recommend it for clients’ “side” investments. “Some call it a Vegas account,” says Scott Hammel, a CFP in Dallas. “Let’s keep this away from our real long-term perspective, make sure it doesn’t become too large a portion of your portfolio.” In a very real sense, Bitcoin is like a single stock, and advisors wouldn’t recommend putting a sizable part of your portfolio into any one company. At most, planners suggest putting no more than 1% to 10% into Bitcoin if you’re passionate about it. “If it was one stock, you would never allocate any significant portion of your portfolio to it,” Hammel says.

telegram from it


Telegram Golang вопросы собеседований
FROM USA