可以创建一个只能与defer一起使用的函数吗?

huangapple go评论103阅读模式
英文:

Can I create a function that must only be used with defer?

问题

例如:

  1. package package
  2. // 亲爱的用户,CleanUp 只能与 defer 一起使用:defer CleanUp()
  3. func CleanUp() {
  4. // 检查调用是否被延迟的一些逻辑
  5. // 执行清理操作
  6. }

在用户代码中:

  1. func main() {
  2. package.CleanUp() // 报错,CleanUp 必须被延迟执行!
  3. }

但是如果用户这样运行代码:

  1. func main() {
  2. defer package.CleanUp() // 做得好,没有报错
  3. }

我已经尝试过的方法:

  1. func DeferCleanUp() {
  2. defer func() { /* 执行清理操作 */ }()
  3. // 但后来我意识到这正好与我所需相反
  4. // 用户不再需要调用 defer CleanUp,但是...
  5. }
  6. // 现在如果 API 被错误使用,也会导致问题:
  7. defer DeferCleanUp() // 一个延迟的嵌套,问题仍然存在。
英文:

For example:

  1. package package
  2. // Dear user, CleanUp must only be used with defer: defer CleanUp()
  3. func CleanUp() {
  4. // some logic to check if call was deferred
  5. // do tear down
  6. }

And in userland code:

  1. func main() {
  2. package.CleanUp() // PANIC, CleanUp must be deferred!
  3. }

But all should be fine if user runs:

  1. func main() {
  2. defer package.CleanUp() // good job, no panic
  3. }

Things I already tried:

  1. func DeferCleanUp() {
  2. defer func() { /* do tear down */ }()
  3. // But then I realized this was exactly the opposite of what I needed
  4. // user doesn't need to call defer CleanUp anymore but...
  5. }
  6. // now if the APi is misused it can cause problems too:
  7. defer DeferCleanUp() // a defer inception xD, question remains.

答案1

得分: 4

好的,以下是翻译好的内容:

好的,根据 OP 的要求,只是为了好笑,我将发布这种通过查看调用堆栈并应用一些启发式方法来解决的笨拙方法。

免责声明:不要在真实代码中使用这个方法。我认为检查延迟执行甚至都不是一件好事。

还要注意:这种方法只在可执行文件和源代码位于同一台机器上时才有效。

链接到 gist: https://gist.github.com/dvirsky/dfdfd4066c70e8391dc5(在 playground 中无法工作,因为无法在那里读取源文件)

  1. package main
  2. import (
  3. "fmt"
  4. "runtime"
  5. "io/ioutil"
  6. "bytes"
  7. "strings"
  8. )
  9. func isDeferred() bool {
  10. // 首先获取调用者的名称
  11. var caller string
  12. if fn, _, _, ok := runtime.Caller(1); ok {
  13. caller = function(fn)
  14. } else {
  15. panic("No caller")
  16. }
  17. // 让我们查看比这个函数高 2 级的调用者 - 第一级是这个函数本身,
  18. // 第二级是 CleanUp()
  19. // 我们想要的是调用 CleanUp() 的那个
  20. if _, file, line, ok := runtime.Caller(2); ok {
  21. // 现在我们实际上需要读取源文件
  22. // 当然,这应该被缓存以避免糟糕的性能
  23. // 我从 runtime/debug 中复制了这个,所以这是合法的 :)
  24. data, err := ioutil.ReadFile(file)
  25. if err != nil {
  26. panic("Could not read file")
  27. }
  28. // 现在让我们读取调用者所在的确切行
  29. lines := bytes.Split(data, []byte{'\n'})
  30. lineText := strings.TrimSpace(string(lines[line-1]))
  31. fmt.Printf("Line text: '%s'\n", lineText)
  32. // 现在让我们应用一些丑陋的经验法则。这是脆弱的部分
  33. // 可以通过正则表达式或实际的 AST 解析来改进,但是...
  34. return lineText == "}" || // 在简单的延迟执行中,我们得到的就是这个
  35. !strings.Contains(lineText, caller) || // 这处理了 defer func() { CleanUp() }() 的情况
  36. strings.Contains(lineText, "defer ")
  37. } // not ok - 意味着我们至少没有从 3 层深处调用
  38. return false
  39. }
  40. func CleanUp() {
  41. if !isDeferred() {
  42. panic("Not Deferred!")
  43. }
  44. }
  45. // 这不应该引发 panic
  46. func fine() {
  47. defer CleanUp()
  48. fmt.Println("Fine!")
  49. }
  50. // 这也不应该引发 panic
  51. func alsoFine() {
  52. defer func() { CleanUp() }()
  53. fmt.Println("Also Fine!")
  54. }
  55. // 这应该引发 panic
  56. func notFine() {
  57. CleanUp()
  58. fmt.Println("Not Fine!")
  59. }
  60. // 从标准库的 runtime/debug 中获取:
  61. // 如果可能,函数返回包含 PC 的函数的名称。
  62. func function(pc uintptr) string {
  63. fn := runtime.FuncForPC(pc)
  64. if fn == nil {
  65. return ""
  66. }
  67. name := fn.Name()
  68. if lastslash := strings.LastIndex(name, "/"); lastslash >= 0 {
  69. name = name[lastslash+1:]
  70. }
  71. if period := strings.Index(name, "."); period >= 0 {
  72. name = name[period+1:]
  73. }
  74. name = strings.Replace(name, "·", ".", -1)
  75. return name
  76. }
  77. func main(){
  78. fine()
  79. alsoFine()
  80. notFine()
  81. }
英文:

Alright, per OPs request and just for laughs, I'm posting this hacky approach to solving this by looking at the call stack and applying some heuristics.

DISCLAIMER: Do not use this in real code. I don't think checking deferred is even a good thing.

Also Note: this approach will only work if the executable and the source are on the same machine.

Link to gist: https://gist.github.com/dvirsky/dfdfd4066c70e8391dc5 (this doesn't work in the playground because you can't read the source file there)

  1. package main
  2. import(
  3. "fmt"
  4. "runtime"
  5. "io/ioutil"
  6. "bytes"
  7. "strings"
  8. )
  9. func isDeferred() bool {
  10. // Let's get the caller's name first
  11. var caller string
  12. if fn, _, _, ok := runtime.Caller(1); ok {
  13. caller = function(fn)
  14. } else {
  15. panic("No caller")
  16. }
  17. // Let's peek 2 levels above this - the first level is this function,
  18. // The second is CleanUp()
  19. // The one we want is who called CleanUp()
  20. if _, file, line, ok := runtime.Caller(2); ok {
  21. // now we actually need to read the source file
  22. // This should be cached of course to avoid terrible performance
  23. // I copied this from runtime/debug, so it's a legitimate thing to do :)
  24. data, err := ioutil.ReadFile(file)
  25. if err != nil {
  26. panic("Could not read file")
  27. }
  28. // now let's read the exact line of the caller
  29. lines := bytes.Split(data, []byte{'\n'})
  30. lineText := strings.TrimSpace(string(lines[line-1]))
  31. fmt.Printf("Line text: '%s'\n", lineText)
  32. // Now let's apply some ugly rules of thumb. This is the fragile part
  33. // It can be improved with regex or actual AST parsing, but dude...
  34. return lineText == "}" || // on simple defer this is what we get
  35. !strings.Contains(lineText, caller) || // this handles the case of defer func() { CleanUp() }()
  36. strings.Contains(lineText, "defer ")
  37. } // not ok - means we were not clled from at least 3 levels deep
  38. return false
  39. }
  40. func CleanUp() {
  41. if !isDeferred() {
  42. panic("Not Deferred!")
  43. }
  44. }
  45. // This should not panic
  46. func fine() {
  47. defer CleanUp()
  48. fmt.Println("Fine!")
  49. }
  50. // this should not panic as well
  51. func alsoFine() {
  52. defer func() { CleanUp() }()
  53. fmt.Println("Also Fine!")
  54. }
  55. // this should panic
  56. func notFine() {
  57. CleanUp()
  58. fmt.Println("Not Fine!")
  59. }
  60. // Taken from the std lib's runtime/debug:
  61. // function returns, if possible, the name of the function containing the PC.
  62. func function(pc uintptr) string {
  63. fn := runtime.FuncForPC(pc)
  64. if fn == nil {
  65. return ""
  66. }
  67. name := fn.Name()
  68. if lastslash := strings.LastIndex(name, "/"); lastslash >= 0 {
  69. name = name[lastslash+1:]
  70. }
  71. if period := strings.Index(name, "."); period >= 0 {
  72. name = name[period+1:]
  73. }
  74. name = strings.Replace(name, "·", ".", -1)
  75. return name
  76. }
  77. func main(){
  78. fine()
  79. alsoFine()
  80. notFine()
  81. }

huangapple
  • 本文由 发表于 2014年12月24日 15:37:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/27633318.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定