Golang Patterns: Difference between revisions

From Adam Colton
Jump to navigation Jump to search
Created page with "== 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..."
 
No edit summary
 
Line 16: Line 16:


By using the literal of Coord, the values can be compared directly.
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{}

Latest revision as of 13:41, 26 July 2018

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{}