Thanks, that's really useful.
It never occurred to me that you could cast it to a type after the error 
has been appended - my attempts to print out the type that was being 
returned didn't show this as an option.

I'll have a play.

Thanks again

On Monday, 2 October 2017 17:20:41 UTC+1, Marvin Renich wrote:
>
> * Marvin Renich <mr...@renich.org <javascript:>> [171002 11:31]: 
> > * Chris Hopkins <cbeho...@gmail.com <javascript:>> [171002 10:52]: 
> > >   out, err := os.Create(potential_file_name) 
> > >   switch t := err.(type) { 
> > >   case *os.PathError: 
> > >     switch t.Err { 
> > >     case os.ErrNotExist: 
> > >       log.Fatal("Invalid filename", potential_file_name) 
> > >     case os.ErrInvalid: 
> > >       log.Fatal("Invalid argument", potential_file_name) 
> > >     default : 
>
> Additionally, os.Create, os.Open, and os.OpenFile all guarantee (via 
> their documentation and the Go 1 Compatibility Guarantee) that if they 
> return a non-nil error, it will be of type *os.PathError, so you could, 
> if you wish, replace the "switch t := err.(type)" with 
> t = err.(*os.PathError) and if it panics, you can file a bug. 
> Furthermore, because the current implementation is extremely unlikely to 
> change, you can simplify even more.  I would write this as: 
>
>     var out, err = os.Create(potential_file_name) 
>     if err != nil { 
>         var pe = err.(*os.PathError) // let it panic or use the ,ok trick 
> as below 
>         var en, ok = pe.Err.(syscall.Errno) // not a Go 1 Compat 
> guarantee, so handle failed type assertion 
>         if !ok { 
>             log.Fatalf("Unexpected error from os.Create: %s\n", pe) 
>         } 
>         switch en { 
>         case syscall.EEXIST: 
>             ... 
>         case syscall.EISDIR: 
>             ... 
>         case syscall.EINVAL: 
>             ... 
>         } 
>     } 
>
> This code is much more readable than the nested type switch that you are 
> using.  Note that os.ErrNotExist and os.ErrInvalid are not of type 
> *os.PathError and os.Create will never return either of them (promised 
> by Go 1 Compat). 
>
> If the !ok test ever succeeds, you know that the implementation of 
> os.OpenFile has changed. 
>
> ...Marvin 
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to