-
-
Save shazow/2cbd5218fc243aaa3aaf to your computer and use it in GitHub Desktop.
Constructors in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tmp | |
import "net" | |
type ServerA struct { | |
Clients map[string]net.Conn | |
} | |
func (srv *ServerA) Accept(conn net.Conn) error { | |
key := conn.RemoteAddr().String() | |
if _, ok := srv.Clients[key]; ok { | |
return ErrCollision | |
} | |
srv.Clients[key] = conn | |
return nil | |
} | |
func init() { | |
// Construct it yourself! | |
srv := &ServerA{ | |
Clients: map[string]net.Conn{}, | |
} | |
Start(srv) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tmp | |
import "net" | |
type serverB struct { | |
clients map[string]net.Conn | |
} | |
func (srv *serverB) Accept(conn net.Conn) error { | |
key := conn.RemoteAddr().String() | |
if _, ok := srv.clients[key]; ok { | |
return ErrCollision | |
} | |
srv.clients[key] = conn | |
return nil | |
} | |
func NewServerB() Server { | |
return &serverB{ | |
clients: map[string]net.Conn{}, | |
} | |
} | |
func init() { | |
// Here's a handy helper constructor. | |
srv := NewServerB() | |
Start(srv) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tmp | |
import "net" | |
type ServerC struct { | |
clients map[string]net.Conn | |
} | |
func (srv *ServerC) Init() { | |
if srv.clients == nil { | |
srv.clients = map[string]net.Conn{} | |
} | |
} | |
func (srv *ServerC) Accept(conn net.Conn) error { | |
key := conn.RemoteAddr().String() | |
if _, ok := srv.clients[key]; ok { | |
return ErrCollision | |
} | |
srv.clients[key] = conn | |
return nil | |
} | |
func init() { | |
// Construct it yourself, but don't forget to Init! | |
srv := ServerC{} | |
srv.Init() | |
Start(&srv) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tmp | |
import ( | |
"errors" | |
"net" | |
) | |
var ErrCollision = errors.New("already connected") | |
type Server interface { | |
Accept(net.Conn) error | |
} | |
func Start(srv Server) { | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment