Deferred close on the input file is fine, no need for closure shenanigans. On
the output file, you'll get cleaner code here by not using defer at all.
outputFile, err := os.Create(outputFileName)
if err != nil {
return err
}
_, err = io.Copy(outputFile, inputFile)
if err != nil {
outputFile.Close() // don't care about the error
return err
}
return outputFile.Close()
> On 16 Feb 2017, at 19:57, Константин Изюмов <[email protected]> wrote:
>
> In my point of view - let`s try that:
>
> -------------------------------------------
> // Copy - copy files
> func Copy(inputFileName, outputFileName string) (err error) {
>
> if len(inputFileName) == 0 {
> return fmt.Errorf("inputFileName is zero: %s", inputFileName)
> }
>
> if len(outputFileName) == 0 {
> return fmt.Errorf("inputFileName is zero: %s", outputFileName)
> }
>
> inputFile, err := os.Open(inputFileName)
> if err != nil {
> return err
> }
> defer func() {
> errFile := inputFile.Close()
> if errFile != nil {
> if err != nil {
> err = fmt.Errorf("%v ; %v", err, errFile)
> } else {
> err = errFile
> }
> }
> }()
>
> outputFile, err := os.Create(outputFileName)
> if err != nil {
> return err
> }
> defer func() {
> errFile := outputFile.Close()
> if errFile != nil {
> if err != nil {
> err = fmt.Errorf("%v ; %v", err, errFile)
> } else {
> err = errFile
> }
> }
> }()
>
> _, err = io.Copy(outputFile, inputFile)
> if err != nil {
> return err
> }
>
> return nil
> }
> -------------------------------------------
>
>
>
>> On Thursday, 17 November 2011 01:41:09 UTC+3, Ian Lance Taylor wrote:
>> Dave Cheney <[email protected]> writes:
>> > On 17/11/2011, at 6:49, Igor Nazarenko <[email protected]> wrote:
>> >
>> >> In many places in the documentation I see the "defer f.Close()" idiom
>> >> used to close files. However, looking at the godoc for os.Close, it
>> >> actually returns an error. What happens to the error return when the
>> >> Close() call is deferred?
>>
>> > It is discarded.
>>
>> So it is probably not a good idea to use this idiom for a file open for
>> writing. But it is fine in practice to do this with a file open only
>> for reading. There is nothing interesting to be done for an error when
>> closing a file open for reading.
>>
>> Ian
>
> --
> 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 [email protected].
> For more options, visit https://groups.google.com/d/optout.
--
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 [email protected].
For more options, visit https://groups.google.com/d/optout.