Golang Patterns

From Adam Colton
Jump to navigation Jump to search

Privacy

Readonly package var

 type priv struct{...}
 var Pub = priv{...}

Pub can only be set internally because priv cannot be created. Useful in cases where you would use a const, but that's not possible with a struct.

Structs

Literal as Key

 type Coord struct{
   X,Y int
 }
 grid := make(map[Coord]string)

By using the literal of Coord, the values can be compared directly.

Guard(?) Method

There's a name for this, I can't remember.

 type Foo interface{
   ...
   guard()
 }
 type fooA struct{...}
 func (fooA) guard()

Prevents external types from fulfilling an interface.

Types

Compiler Type Assert

 var _ SomeInterface = &SomeType{}