Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Here we make several attempts to imagine the best ever semantic for type
- // initialization with numerous parameters.
- package main
- import (
- "errors"
- "strconv"
- "testing"
- )
- var Err222 = errors.New("стватья 222 УК РФ")
- type FooOptions struct {
- Host string
- Port uint16
- }
- type Foo struct {
- opts FooOptions
- }
- func (f *Foo) Hostname() string {
- return f.opts.Host + ":" + strconv.Itoa(int(f.opts.Port))
- }
- // Pack parameters into structure and pass it to type constructor.
- func NewFoo1(opts FooOptions) (*Foo, error) {
- if opts.Port == 0 {
- opts.Port = 8080
- } else if opts.Port == 1488 {
- return nil, Err222
- }
- return &Foo{opts}, nil
- }
- func TestNewFoo1(t *testing.T) {
- var foo, err = NewFoo1(FooOptions{Host: "localhost"})
- if err != nil {
- t.Errorf("NewFoo1(): %s", err)
- }
- if foo.Hostname() != "localhost:8080" {
- t.Errorf("wrong hostname: %s", foo.Hostname())
- }
- }
- // Let FooOptions struct be Foo type builder.
- func (o *FooOptions) NewFoo2() (*Foo, error) {
- if o.Port == 0 {
- o.Port = 8080
- } else if o.Port == 1488 {
- return nil, Err222
- }
- return &Foo{*o}, nil
- }
- func TestNewFoo2(t *testing.T) {
- var opts = FooOptions{Host: "localhost"}
- var foo, err = opts.NewFoo2()
- if err != nil {
- t.Errorf("NewFoo2(): %s", err)
- }
- if foo.Hostname() != "localhost:8080" {
- t.Errorf("wrong hostname: %s", foo.Hostname())
- }
- }
- // Enumerate option functors that mutate the state of an instantce of Foo type.
- type option func(foo *Foo) error
- func Host(value string) option {
- return func(f *Foo) error {
- f.opts.Host = value
- return nil
- }
- }
- func Port(value uint16) option {
- return func(f *Foo) error {
- if value == 0 {
- value = 8080
- } else if value == 1488 {
- return Err222
- }
- f.opts.Port = value
- return nil
- }
- }
- func NewFoo3(opts ...option) (*Foo, error) {
- foo := &Foo{}
- foo.opts = FooOptions{
- Port: 8080, // XXX: weird
- }
- for _, opt := range opts {
- if err := opt(foo); err != nil {
- return nil, err
- }
- }
- return foo, nil
- }
- func TestNewFoo3(t *testing.T) {
- var foo, err = NewFoo3(Host("localhost"))
- if err != nil {
- t.Errorf("NewFoo2(): %s", err)
- }
- if foo.Hostname() != "localhost:8080" {
- t.Errorf("wrong hostname: %s", foo.Hostname())
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment