The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
Mohanson

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

  •  
  •   Mohanson · Mar 16, 2022 · 2129 views
    This topic created in 1544 days ago, the information mentioned may be changed or developed.

    更新了自己的 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 replies    2022-03-16 18:14:58 +08:00
    Mohanson
        1
    Mohanson  
    OP
       Mar 16, 2022
    a935855375
        2
    a935855375  
       Mar 16, 2022
    一般 err 都不会 panic ,可能会加工一下,return 到上一层
    sy20030260
        3
    sy20030260  
       Mar 16, 2022
    error 的处理逻辑最好是可以作为参数传入的而不是默认 panic ?类似传入一个 func(err) ,这样更 general 一点,也比较接近 try-catch 的范式
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4544 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 63ms · UTC 01:04 · PVG 09:04 · LAX 18:04 · JFK 21:04
    ♥ Do have faith in what you're doing.