Last active
July 31, 2018 21:28
-
-
Save AxelRHD/05d167e08d96d1c2e8d5120708885556 to your computer and use it in GitHub Desktop.
Golang Snippets
This file contains hidden or 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 main | |
import ( | |
"fmt" | |
"sync" | |
"time" | |
) | |
type message struct { | |
data int | |
wg *sync.WaitGroup | |
} | |
func main() { | |
var wg sync.WaitGroup | |
c := make(chan message) | |
go process(c) | |
for i := 1; i < 6; i++ { | |
fmt.Printf("S -> %d\n", i) | |
wg.Add(1) | |
c <- message{i, &wg} | |
time.Sleep(time.Millisecond * 500) | |
} | |
wg.Wait() | |
fmt.Println("Processing done.") | |
} | |
func process(c chan message) { | |
for { | |
msg := <-c | |
printer(&msg) | |
} | |
} | |
func printer(m *message) { | |
defer m.wg.Done() | |
fmt.Println("ping") | |
time.Sleep(time.Second * 2) | |
fmt.Printf("G <- %d\n", m.data) | |
} |
This file contains hidden or 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 main | |
import ( | |
"bytes" | |
"fmt" | |
"io" | |
) | |
func main() { | |
me := person{ | |
Name: "Axel", | |
Age: 35, | |
Admin: true, | |
} | |
var b bytes.Buffer | |
me.Write(&b) | |
fmt.Printf("%s", b.String()) | |
} | |
type person struct { | |
Name string | |
Age int | |
Admin bool | |
} | |
func (p *person) Write(w io.Writer) { | |
out := fmt.Sprintf("%+v\t%+v\t%+v\n", | |
p.Name, p.Age, p.Admin) | |
w.Write([]byte(out)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment