V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
Hooooooey
V2EX  ›  程序员

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

  •  
  •   Hooooooey · 12 小时 26 分钟前 · 210 次点击

    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 公众号

    1 条回复    2025-03-05 22:26:07 +08:00
    anivie
        1
    anivie  
       8 小时 46 分钟前
    复制到里面的网址里运行被报错了?为什么那里不能用逗号,版本问题吗
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1182 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 18ms · UTC 23:12 · PVG 07:12 · LAX 15:12 · JFK 18:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.