Skip to content

Instantly share code, notes, and snippets.

View 0xc0d's full-sized avatar

Ali Josie 0xc0d

View GitHub Profile
@0xc0d
0xc0d / BadOrderedStruct_Compiler.go
Last active October 27, 2020 15:43
What happen to struct typed inside comiler
type BadOrderedPerson struct {
Veteran bool // 1 byte
_ [7]byte // 7 byte: padding for alignment
Name string // 16 byte
Age int32 // 4 byte
_ struct{} // to prevent unkeyed literals
// zero sized values, like struct{} and [0]byte occurring at
// the end of a structure are assumed to have a size of one byte.
// so padding also will be addedd here as well.
@0xc0d
0xc0d / badOrderedStruct.go
Last active October 25, 2020 15:14
bad ordered struct
type BadOrderedPerson struct {
Veteran bool // 1 byte
Name string // 16 byte
Age int32 // 4 byte
}
type OrderedPerson struct {
Name string
Age int32
Veteran bool
@0xc0d
0xc0d / unguaranteed_chan.go
Last active October 25, 2020 12:21
Sending into unguaranteed channel
func doReq(timeout time.Duration) obj {
// ch :=make(chan obj)
ch := make(chan obj, 1)
go func() {
obj := do()
ch <- result
} ()
select {
case result = <- ch :
return result
@0xc0d
0xc0d / Loop4_fix.go
Created October 25, 2020 12:01
Using defer in loop
var mutex sync.Mutex
type Person struct {
Age int
}
persons := make([]Person, 10)
for _, p := range persons {
func() {
mutex.Lock()
defer mutex.Unlock()
p.Age = 13
@0xc0d
0xc0d / Loop4.go
Last active October 25, 2020 11:53
Using defer in loop
var mutex sync.Mutex
type Person struct {
Age int
}
persons := make([]Person, 10)
for _, p := range persons {
mutex.Lock()
// defer mutex.Unlock()
p.Age = 13
mutex.Unlock()
@0xc0d
0xc0d / Loop3.go
Created October 25, 2020 03:36
Call WaitGroup.Wait in loop
var wg sync.WaitGroup
wg.Add(len(tasks))
for _, t := range tasks {
go func(t *task) {
defer group.Done()
}(t)
// group.Wait()
}
group.Wait()
@0xc0d
0xc0d / Loop2.go
Created October 25, 2020 03:28
Using goroutines on loop iterator variables
list := []int{1, 2, 3}
for _, v := range list {
go func() {
fmt.Printf("%d ", v)
}()
}
@0xc0d
0xc0d / Loop1_fix.go
Last active October 25, 2020 03:26
Using reference to loop iterator variable
in := []int{1, 2, 3}
var out []*int
for _, v := range in {
v := v
out = append(out, &v)
}
fmt.Println("Values:", *out[0], *out[1], *out[2])
fmt.Println("Addresses:", out[0], out[1], out[2])
@0xc0d
0xc0d / Loop1.go
Last active October 25, 2020 03:25
Using reference to loop iterator variable
in := []int{1, 2, 3}
var out []*int
for _, v := range in {
out = append(out, &v)
}
fmt.Println("Values:", *out[0], *out[1], *out[2])
fmt.Println("Addresses:", out[0], out[1], out[2])
@0xc0d
0xc0d / poolBench_test.go
Created October 24, 2020 18:40
sync.Pool Benchmark test
type Person struct {
Age int
}
var personPool = sync.Pool{
New: func() interface{} { return new(Person) },
}
func BenchmarkWithoutPool(b *testing.B) {
var p *Person