Defer method for using the Go language in Delphi XE

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

When implementing a function, if the intermediate steps go wrong, you need to release the resources and exit the function, which is cumbersome and error-prone. The go language author is disappointed with the experience of software development over the past decade, and in response to this problem, he brings the defer method that allows you to exit anywhere within the function to make sure you have a chance to clean up. A similar approach can be implemented in Delphi XE. Program Demo_defer;

{$APPTYPE CONSOLE}

Uses
Sysutils,
Coroutineunit; Or use this unit ... It's still in the annex.

Begin
Tproc (procedure ()//This function demonstrates copying the contents of a file into another file.
Var
F1, F2:integer; Two file pointers, F1 content to be copied into the F2.
Begin
F1:=fileopen (' F1 ', fmopenread); Open F1 file
The defer (procedure ()//defer function saves the parameter function and then calls it when the function it belongs to exits.
Begin
FileClose (F1);
Writeln (' F1 is closed ');
End);
F2:=fileopen (' F2 ', fmopenwrite); Open F2 file again
If F2=-1 then BEGIN
Writeln (' F2 open failed ');
Exit; Take a decisive exit without considering the state of F1
End
Copycontent (F1, F2); Start copy (assuming this copy function exists)
FileClose (F2);
End) ();

READLN;
End.


In the past, when dealing with this situation, you need to determine whether F2 open fails, if it fails, you need to close F1 and then exit, if this function is complex, you may forget to close, and in this way, make sure that no matter how many exits you write, the code that closes F1 is executed.

The result of the actual output is:
F2 Open failed
F1 is closed.

Related downloads:
Examples of defer methods using the Go language in Delphi XE
Source: HTTP://WWW.CNPACK.ORG/SHOWDETAIL.PHP?ID=699&LANG=ZH-CN

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.