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

Golang 下面的函数可能返回 error 么

  •  
  •   imherer · 2021-03-03 15:40:02 +08:00 · 1267 次点击
    这是一个创建于 1122 天前的主题,其中的信息可能已经有所发展或是发生改变。
    func test(params ...interface{}) error {
        if len(params) > 0 {
    		b, err := json.Marshal(params)
    		if err != nil {
    		     return err
    		}
    		fmt.Println(b)
    	}
    
        return nil
    }
    
    8 条回复    2021-03-03 17:58:04 +08:00
    wunonglin
        1
    wunonglin  
       2021-03-03 15:42:14 +08:00
    json.Marshal 不就有 err 么。。。
    这是面试题还是啥?
    wunonglin
        2
    wunonglin  
       2021-03-03 15:43:10 +08:00
    而且你这个 interface 要 for 吧?
    imherer
        3
    imherer  
    OP
       2021-03-03 15:43:49 +08:00
    @wunonglin error 会有值吗?
    imherer
        4
    imherer  
    OP
       2021-03-03 15:44:38 +08:00
    @wunonglin 不用 for,就是按数组去转成 json
    HiShan
        5
    HiShan  
       2021-03-03 15:50:30 +08:00   ❤️ 2
    json 不支持的类型就会返回 error 例如 func
    mauve
        6
    mauve  
       2021-03-03 17:07:58 +08:00
    如果 params 的类型是 channel, complex, 或者 function 的话,那么这个 test 函数就会返回 error
    此外,还有一些回导致 循环依赖 /循环引用 的数据结构也会导致错误
    在这里查 https://pkg.go.dev/encoding/json#Marshal

    Channel, complex, and function values cannot be encoded in JSON. Attempting to encode such a value causes Marshal to return an UnsupportedTypeError.

    JSON cannot represent cyclic data structures and Marshal does not handle them. Passing cyclic structures to Marshal will result in an error.
    mauve
        7
    mauve  
       2021-03-03 17:24:10 +08:00
    我试了一下如果 test 函数的入参是一组参数的话,debug 时 也是会跳到 return err 这一行,err 的类型和 入参是单个 channel/complex/function 时是一种类型的错误:*encoing/json.UnsupportedTypeError

    ```go
    func main() {
    ss := make(chan int)
    xx := make(chan int)
    test(ss, xx) // will return err | *encoing/json.UnsupportedTypeError
    }
    ```
    imherer
        8
    imherer  
    OP
       2021-03-03 17:58:04 +08:00
    @mauve 感谢~
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2806 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 14:57 · PVG 22:57 · LAX 07:57 · JFK 10:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.