TypeOf without an instance and passing result to a func

Yes, it’s possible. The trick is to start from a pointer to the type (whose value can be a typed nil, that’s perfectly OK), and then use Type.Elem() to get the reflect.Type descriptor of the pointed type (the base type). See some examples: t := reflect.TypeOf((*int)(nil)).Elem() fmt.Println(t) t = reflect.TypeOf((*http.Request)(nil)).Elem() fmt.Println(t) t = reflect.TypeOf((*os.File)(nil)).Elem() fmt.Println(t) … Read more

golang multiple case in type switch

This is normal behaviour that is defined by the spec (emphasis mine): The TypeSwitchGuard may include a short variable declaration. When that form is used, the variable is declared at the beginning of the implicit block in each clause. In clauses with a case listing exactly one type, the variable has that type; otherwise, the … Read more

How to inspect slice header?

The slice header is represented by the reflect.SliceHeader type: type SliceHeader struct { Data uintptr Len int Cap int } You may use package unsafe to convert a slice pointer to *reflect.SliceHeader like this: sh := (*reflect.SliceHeader)(unsafe.Pointer(&newSlice2)) And then you may print it like any other structs: fmt.Printf(“%+v”, sh) Output will be (try it on … Read more

Go exec.Command() – run command which contains pipe

Passing everything to bash works, but here’s a more idiomatic way of doing it. package main import ( “fmt” “os/exec” ) func main() { grep := exec.Command(“grep”, “redis”) ps := exec.Command(“ps”, “cax”) // Get ps’s stdout and attach it to grep’s stdin. pipe, _ := ps.StdoutPipe() defer pipe.Close() grep.Stdin = pipe // Run ps first. … Read more

Streaming commands output progress

The code you posted works (with a reasonable command executed). Here is a simple “some long running task” written in Go for you to call and test your code: func main() { fmt.Println(“Child started.”) time.Sleep(time.Second*2) fmt.Println(“Tick…”) time.Sleep(time.Second*2) fmt.Println(“Child ended.”) } Compile it and call it as your command. You will see the different lines appear … Read more