• 请不要在回答技术问题时复制粘贴 AI 生成的内容
Hooooooey
V2EX  ›  程序员

小技巧: MoonBit-Array pattern 中用字符串字面量和常量匹配子字符串

  •  
  •   Hooooooey · Mar 5, 2025 · 1303 views
    This topic created in 445 days ago, the information mentioned may be changed or developed.

    Array pattern 的小技巧,原来在匹配时,可以直接用字符串字面量和常量来匹配子字符串,而不用逐个字符进行匹配。MoonBit 最新的模式匹配的用法,发现可以这样处理不同协议的 URL 。例如,直接用 [..HTTP, ..path] 来匹配以 http:// 开头的字符串,或者用 [..HTTPS, ..path] 来匹配 https:// 开头的字符串。

    const HTTP = "http://"
    const HTTPS = "https://"
    
    fn main {
      let str = "https://try.moonbitlang.com"
      match str {
        [..HTTP, .. path] => println(path),
        [..HTTPS, .. path] => println(path),
        _ => println("unexpected protocol")
      }
    }
    

    以上来源为 MoonBit 公众号

    2 replies    2025-03-06 10:08:35 +08:00
    anivie
        1
    anivie  
       Mar 5, 2025
    复制到里面的网址里运行被报错了?为什么那里不能用逗号,版本问题吗
    Hooooooey
        2
    Hooooooey  
    OP
       Mar 6, 2025
    @anivie 7 、8 行最末端的逗号去掉试试,以及不需要逗号是因为 MoonBit 有自动分号插入
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5432 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 03:53 · PVG 11:53 · LAX 20:53 · JFK 23:53
    ♥ Do have faith in what you're doing.