Skip to content

Instantly share code, notes, and snippets.

@sent-hil
Created November 7, 2012 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sent-hil/4034166 to your computer and use it in GitHub Desktop.
Save sent-hil/4034166 to your computer and use it in GitHub Desktop.
HS - Nov 7
--------------------------
Interfaces vs. Duck typing
Duck typing isn't really about checking whether the things you need are there and then using them.
Duck typing is about just using what you need.
Interfaces are named collections of method signatures.
https://gobyexample.com/interfaces
--------------------------
```go
type connection struct {
// no need to use a pointer since net.Conn is already a pointer
nc net.Conn
send chan string
}
```
If we did use `*net.Conn`, then `connection.nc.Read()` won't work, since we're calling `Read()`
on a pointer, we've to do `(*connection.nc).Read()`.
--------------------------
What are the best types to pass as messages between channels?
```go
var h = hub{
connections: make(map[*connection]bool),
// accepts {connection => [byte]}
broadcast: make(chan map[*connection]byte),
register: make(chan *connection),
unregister: make(chan *connection),
}
```
--------------------------
Listening in non-buffered channels will throw error, unless in a goroutine.
```go
package main
import "fmt"
func main () {
messages := make(chan string)
// error
messages <- "ping"
msg := <-messages
fmt.Println(msg)
}
```
```go
package main
import "fmt"
func main () {
messages := make(chan string)
// no error
go func() { messages <- "ping" }()
msg := <-messages
fmt.Println(msg)
}
```
```go
package main
import "fmt"
func main () {
// buffered channel that takes 1 msg
messages := make(chan string, 1)
// no error
messages <- "ping"
msg := <-messages
fmt.Println(msg)
}
```
--------------------------
Pass functions to channels
```go
var c chan func()(int, int, string)
c <- func()(int, int, string){return 1, 2, "three"}
i1, i2, s1 := (<-c)()
// or
func makeTuple(i1, i2 int, s string) func()(int, int, string) {
return func()(int, int, string) { return i1, i2, s }
}
c <- makeTuple(1, 2, "three")
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment