need type assertion, how to fix ???

987 views
Skip to first unread message

gocss

unread,
Dec 13, 2015, 10:02:13 PM12/13/15
to golang-nuts
Trying to understand how to make this work:
part 1 compiles and says what type is for stdout ,
in part2 I want to explicitly define with var stdout *os.File but get some type assertion issue
can someone explain how to satisfy the compiler and still explicitly define stdout,
(I want to use this elsewhere) ????

// part 1
package main

import (
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("ls", "-lhrtR", "/home")
    stdout, _ := cmd.StdoutPipe()
    fmt.Printf("%T\n", stdout)  //prints *os.File
}

//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

css

~  



Jesse McNelis

unread,
Dec 13, 2015, 10:29:04 PM12/13/15
to gocss, golang-nuts
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

gocss

unread,
Dec 14, 2015, 6:18:39 AM12/14/15
to golang-nuts

is it possible to do the Type assertion without introducing the stdout1 variable ?

something like this:     stdout, _ = cmd.StdoutPipe().(*os.File)

but need something different because StdoutPipe() has multiple return values?

 

Jesse McNelis

unread,
Dec 14, 2015, 6:58:52 AM12/14/15
to gocss, golang-nuts

Nope, you'll need to check that error value too anyway.

simon place

unread,
Dec 14, 2015, 4:36:45 PM12/14/15
to golang-nuts
you could wrap it in a function that returns only one value, which handles the error inside

Reply all
Reply to author
Forward
0 new messages