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

2021-03-03 15:40:02 +08:00
 imherer
func test(params ...interface{}) error {
    if len(params) > 0 {
		b, err := json.Marshal(params)
		if err != nil {
		     return err
		}
		fmt.Println(b)
	}

    return nil
}
1283 次点击
所在节点    Go 编程语言
8 条回复
wunonglin
2021-03-03 15:42:14 +08:00
json.Marshal 不就有 err 么。。。
这是面试题还是啥?
wunonglin
2021-03-03 15:43:10 +08:00
而且你这个 interface 要 for 吧?
imherer
2021-03-03 15:43:49 +08:00
@wunonglin error 会有值吗?
imherer
2021-03-03 15:44:38 +08:00
@wunonglin 不用 for,就是按数组去转成 json
HiShan
2021-03-03 15:50:30 +08:00
json 不支持的类型就会返回 error 例如 func
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
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
2021-03-03 17:58:04 +08:00
@mauve 感谢~

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/758047

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX