openlang

F# 检查文件是否存在时的取反操作

我用这段代码在文件不存在时报错。

  if !File.Exists(inputPath) then
      printfn "inputPath doesn't exist %s" inputPath; failwith "stop"

结果却出现了这个错误。我哪里理解错了?

  error FS0001: This expression was expected to have type
      bool ref    
  but here has type
      bool
从英语翻译查看原文

后续讨论 2

顺着彼此的依据读下去
  1. 固定链接

    ! 在 F# 中的含义不同,它的定义如下。

      type 'a ref { Contents : 'a }
      let (!) (cell : ref 'a) = cell.Contents

    失败是因为你传入了 bool,而 ! 要求的操作数是 bool ref。

    改用 not 函数。

      if not(File.Exists(inputPath)) then
          printfn "inputPath doesn't exist %s" inputPath; failwith "stop"
    从英语翻译查看原文

同一个问题的其他角度

  1. `String::from_utf8` 失败时会把字节还给你

    消耗型 API 得决定失败时那个值怎么处理。String::from_utf8 按值接收 Vec<u8>,失败时由错误持有它。 它会打印 bad byte at 2, 4 bytes back。没有拷贝,调用方在一个值里同时拿回缓冲区和出错的偏移。m…

    回复 0最近活动 rust
  2. except ValueError 在 gather(return_exceptions=True) 外面永远不执行,然后 ValueError 引发 TypeError

    我在客户回访前跑一个小脚本,根据三项指标给每个客户的网站打分,每个客户的权重从他们的分析接口获取。获取是通过 asyncio.gather 做的,并且设了 return_exceptions=True,所以一个客户出问题不会取消其他的,对吧?响应为空…

    回复 5最近活动 python
  3. errdefer 里的 free 在成功路径上泄漏了

    一个测试泄漏了内存,而且泄漏出在成功的那条路径上。函数分配了一个临时缓冲区,解析出一个归调用方所有的结果,并用 errdefer allocator.free(scratch) 释放这个临时缓冲区。所有错误路径都释放了它。成功返回却没有,测试结束时…

    回复 2最近活动 zig