go语言中使用defer关键字,实现资源的自动释放,让异常处理方面了许多,对于提高代码的可读性,可维护性有很大好处,其实在C++、python、java、ruby中也有相应的方法自动关闭资源。
f, err := os.Open('hello.txt')if err != nil { log.Printf("%s", err) return}defer f.Close()?do something with file
c++: 可以使用shared_ptr, 或者自己实现一个类用于关闭文件。C++中,超过对象的作用域析构函数马上会执行,因此实现这个功能很简单。
FILE* f = fopen("hello.txt", "r");if (f == NULL) { fprintf(stderr, "%s", strerror(errno)); return;}shared_ptr defer(f, fclose);// do something with file
python (>=2.5): 可以使用with,这篇博客介绍介绍了with原理。
try: with open('hello.txt') as f: do something with fileexcept IOError: print 'oops!'
java: (java <= 1.6) 比较土,只能在finally里关闭
File file = new File('hello.txt')InputStream in = null;try { in = new FileInputStream(file); // do something with inputStream} catch (FileNotFoundException ex) { System.err.println("Missing file");} finally { if (in != null) { try { in.close() } catch (IOException e) { } }}
java 1.7: java1.7中实现AutoCloseable的类可以自动释放资源。
File file = new File('hello.txt');try (InputStream in = new FileInputStream(file)) {} catch (FileNotFoundException e) { System.err.println("Missing file");}
ruby 也可以实现文件的自动关闭
File.open('hello.txt', 'r') do |f| do something with fend
原文地址:各类语言中资源的自动释放, 感谢原作者分享。 现在睡觉的话,会做梦;而现在学习的话,会让梦实现。