Apr 19, 2017

[Go] code snippet

http://www.tapirgames.com/blog/golang-tricks
Get the range index.
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 goroutin forever(using select).
package main

import "time"

func main() {
 go func() {
  for {
   time.Sleep(time.Second)
  }
 }()
 
 select{} // block here for ever
}


Bits manipulte.
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

import "unsafe"

const Is64bitOS = unsafe.Sizeof(1) / 8
const WordBits = unsafe.Sizeof(1) * 8


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
}


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{}
}


Design:
Shadow unwanted variables and types to avoid misusing them carelessly.
i.e The POWER of blocks (c++ alike)
import "database/sql"

func Exec(db *sql.DB, sqlstr string) error {
 // using db ...
 // ...

 // do transaction
 tx, err := db.Begin()
 if err != nil {
  return err
 }
 
 // sql.DB and sql.Tx have many same methods,
 // to avoid misusing the db variable below,
 // we can shaddow it.
 {
  type db complex64 // shaddow db
  
  // _, err := db.Exec(sqlstr) 
  // if we call the above line, compiler will report error.
  _, err := tx.Exec(sqlstr)
  if err != nil {
   tx.Rollback()
   return err
  }

  return tx.Commit()
 }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.