V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
Mohanson
V2EX  ›  Go 编程语言

doa: 使用 Go generics 简化错误处理

  •  
  •   Mohanson · 2022-03-16 15:58:56 +08:00 · 1562 次点击
    这是一个创建于 765 天前的主题,其中的信息可能已经有所发展或是发生改变。

    更新了自己的 doa 库:

    https://github.com/godump/doa

    这个迷你库的目的是当检测到 error 时立即 panic 掉程序.

    核心代码其实就一行函数定义:

    // Try will give you the embedded value if there is no error returns. If instead error then it will panic.
    func Try[T any](a T, err error) T {
    	if err != nil {
    		panic(err)
    	}
    	return a
    }
    
    3 条回复    2022-03-16 18:14:58 +08:00
    Mohanson
        1
    Mohanson  
    OP
       2022-03-16 16:00:49 +08:00
    a935855375
        2
    a935855375  
       2022-03-16 17:27:01 +08:00
    一般 err 都不会 panic ,可能会加工一下,return 到上一层
    sy20030260
        3
    sy20030260  
       2022-03-16 18:14:58 +08:00
    error 的处理逻辑最好是可以作为参数传入的而不是默认 panic ?类似传入一个 func(err) ,这样更 general 一点,也比较接近 try-catch 的范式
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   928 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:12 · PVG 06:12 · LAX 15:12 · JFK 18:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.