-
如果range over slice時對slice作改動,是否會改動slice ? range over slice will copy the original value.
-
how to compare 2 struct value ?
reflect.DeepEqual -
how to verify that struct actually implement a Interface ?
var _ Interface = (*Struct_Should_Implement)(nil) -
convert
[]bytetostring是否會造成 copy ?- yes
- string is immutable but
[]byteis mutable
-
Modifying map while iterating over it ?
- unpredictable
- If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped.
- If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced.
-
How to check if a slice is sorted ?
- sort.IsSorted()
- sort.SliceIsSorted(), passing a less()
-
marshal json what is the result ?
type J struct {
a string
b string `json:"B"`
C string
D string `json:"DD"`
}
j := J{
a: "1",
b: "2",
C: "3",
D: "4",
}
fmt.Printf("j = %+v\n", j) -
make vs new
- both for memory allocation
- new will allocate the zero value of type
- make can only allocate map, slice, chan
-
can we address the map ?
- map is not addressable
- when hash table is reorganized, the address will change.
m := make(map[string]int) fmt.Println(&m["qcrao"]) // cannot take the address of m["qcrao"]
-
use case of
tag- json marshall unmarshal
- db: sqlx column mapping
- form: gin validation for form
- binding: gin binding for validation
-
fmt.Printfwith%v%+v%#v
type animal struct {
name string
age int
}
a := animal{name: "cat", age: 2}
fmt.Printf("%v\n", a) // {cat 2}
fmt.Printf("%+v\n", a) // {name:cat age:2}
fmt.Printf("%#v\n", a) // main.animal{name:"cat", age:2}- the execution order of import, const, var, init(), main() import –> const –> var –>init()–>main()
- Channel deadlock的情況
- read from
nilchannel - write to full channel
- write to closed channel
- all grouting blocked
- read from
- 讀closed channel 的行為?
- 一直讀到 zero value
- 不會deadlock
- 解決: 把原chan 設為 nil
- use wait group to wait for multiple goroutines returns
- use channel to block channel sender or channel receiver
- use channel if we need specific order of goroutine execution
- pass context within chain of goroutine to control / cancel .
- use select to organize multiple channels
- map is
hmapstruct with pointerbucketsto buckets array of2^Bbuckets. - bucket is
bmapstruct with 8 buckets, each bucket stores an key value pair
- Graceful shutdown
- start a goroutine for
server.listenAndServe()in background - main thread blocked and listen to os termination signal (
syscall.SIGTERM) - if received os signal, use context with timeout and call server to shutdown.
- start a goroutine for