Switch cases can be separated by coma:
func shouldEscape(c byte) bool {
switch c {
case ' ', '?', '&', '=', '#', '+', '%':
return true
}
return false
}
Go Daily Tips
Thursday, January 15, 2015
Sunday, January 11, 2015
Alternative to label
Get out of a for/select loop without using labels:
func main() {
OUT:
for {
select {
case ... ):
...
default:
break OUT
}
}
....
}
Refactoring out the for loop:
func main() {
...
doSomething()
...
}
func doSomething() {
for {
select {
case ...:
...
default:
return
}
}
}
func main() {
OUT:
for {
select {
case ... ):
...
default:
break OUT
}
}
....
}
Refactoring out the for loop:
func main() {
...
doSomething()
...
}
func doSomething() {
for {
select {
case ...:
...
default:
return
}
}
}
Saturday, January 10, 2015
Basic dependency management
To install all the dependencies of a package:
$ go list -f '{{ join .Imports "\n" }}' | xargs go get
$ go list -f '{{ join .Imports "\n" }}' | xargs go get
Thursday, January 8, 2015
TestMain in go 1.4 testing module
Provide setup and teardow to your test with g0 1.4 testing module:
func setUp() {
...
}
func tearDown() {
...
}
func TestMain(m *testing.M) {
setUp()
r := m.Run()
tearDown() // cannot run tearDown in a defer because of os.Exit
os.Exit(r)
}
func TestFoo(t *testing.T) {
...
...
}
func TestBar(t *testing.T) {
...
...
}
Wednesday, January 7, 2015
Exiting carefully
os.Exit() terminates immediately and deferred functions are
not run.
Tuesday, January 6, 2015
Notes on expressions
Expressions
"x |= y" is equivalent to "x = x | y", just like "x += y" is equivalent to "x = x + y".
Same for &= .
"x |= y" is equivalent to "x = x | y", just like "x += y" is equivalent to "x = x + y".
Same for &= .
Monday, January 5, 2015
Check interface implementation
- Check if a variable implements a given interface and obtain the variable in the context of that interface:
m, ok := val.(json.Marshaler)
-For example:
if _, ok := val.(json.Marshaler); ok {
fmt.Printf("value %v of type %T implements json.Marshaler\n", val, val)
}
m, ok := val.(json.Marshaler)
-For example:
if _, ok := val.(json.Marshaler); ok {
fmt.Printf("value %v of type %T implements json.Marshaler\n", val, val)
}
Subscribe to:
Posts (Atom)