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

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

  •  
  •   imherer · Mar 3, 2021 · 2112 views
    This topic created in 2081 days ago, the information mentioned may be changed or developed.
    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 replies  •  2021-03-03 17:58:04 +08:00
    shakaraka
    shakaraka
    Mar 3, 2021
    1
    json.Marshal 不就有 err 么。。。
    这是面试题还是啥?
    shakaraka
    shakaraka
    Mar 3, 2021
    2
    而且你这个 interface 要 for 吧?
    imherer
    imherer
    OP
    Mar 3, 2021
    3
    @wunonglin error 会有值吗?
    imherer
    imherer
    OP
    Mar 3, 2021
    4
    @wunonglin 不用 for,就是按数组去转成 json
    HiShan
    HiShan
    Mar 3, 2021❤️2
    5
    json 不支持的类型就会返回 error 例如 func
    mauve
    mauve
    Mar 3, 2021
    6
    如果 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
    mauve
    Mar 3, 2021
    7
    我试了一下如果 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
    imherer
    OP
    Mar 3, 2021
    8
    @mauve 感谢~
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2764 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 10:23 · PVG 18:23 · LAX 02:23 · JFK 05:23
    ♥ Do have faith in what you're doing.