On Mon, Dec 14, 2015 at 2:02 PM, gocss <
g...@curtissystemssoftware.com> wrote:
> //part 2
> so why can I not do this?
> package main
>
> import (
> "fmt"
> "os"
> "os/exec"
> )
>
> func main() {
> cmd := exec.Command("ls", "-lhrtR", "/home")
> var stdout *os.File
> stdout, _ = cmd.StdoutPipe() // this is main.go:12
> fmt.Printf("%T\n", stdout)
> }
> go install:
> ./main.go:12: cannot assign io.ReadCloser to stdout (type *os.File) in
> multiple assignment: need type assertion
Because cmd.StdoutPipe() returns an io.ReadCloser interface value and
you've declared stdout to be a concrete *os.File.
The concrete type of the io.ReadCloser is an *os.File so you can do a
'type assertion' to get the concrete *os.File out of the io.ReadCloser
interface value.
eg.
stdout1, _ := cmd.StdoutPipe()
stdout := stdout1.(*os.File) //this will panic if stdout1 doesn't have
a concrete value of the type *os.File
You can read more about type assertions in the language spec.
https://golang.org/ref/spec#Type_assertions