This article will show some Go syntax tricks (there are really not many tricks in Go).

Simulate for i in 0..N in some other languages

package main import "fmt" func main() { for i := range (*[10]int)(nil) { // int can be replaced with any type fmt.Println(i) } for i := range [10][0]int{} { // int can be replaced with any type fmt.Println(i) } for i := range [10]struct{}{} { fmt.Println(i) } }

Block main goroutine for ever

package main import "time" func main() { go func() { for { time.Sleep(time.Second) } }() select{} // block here for ever } When main goroutine exits, Go program will exist too. There are many ways to achieve this, here we select the tiniest one.

Calculate OS word size at compile time

const MaxUint = ^uint(0) const MaxInt = int(^uint(0) >> 1) const Is64bitOS = ^uint(0) >> 63 // 1 or 0 const WordBits = 32 << (^uint(0) >> 63) // 64 or 32 We can also use unsafe.Sizeof to check size of int . import "unsafe" const Is64bitOS = unsafe.Sizeof(1) / 8 const WordBits = unsafe.Sizeof(1) * 8 The trick is not Go specified.We can also useto check size of

Put compile-time assertion code in functions identified with the blank identifier

type I interface { f() } func _() { var _ I = T{} // assert T implements I var _ I = (*T)(nil) // assert *T implements I } type T struct{} func (t T) f() {} const M = 8 const N = 8 func _() { // methods to assert N >= M var _ [N-M]int type _ [N-M]int const _ uint = N-M // methods to assert M == N var _ [M-N]int; var _ [N-M]int type _ [M-N]int; type _ [N-M]int const _, _ uint = M-N, N-M } This may be not a real trick, in fact, you can use any names for such functions. But the blank identifier give people the impression that the functions will never be called.

Use recover to restart goroutine automatically

package main import ( "time" "fmt" ) func neverExist() { time.Sleep(time.Second) panic("crashed.") } func autoRestart(f func()) { defer func() { recover() fmt.Println("restart") go autoRestart(f) }() f() } func main() { go autoRestart(neverExist) select{} }

Shadow unwanted variables and types to avoid misusing them carelessly