2022-07-20:以下go语言代码是关于json 和 context的,输出什么?A:{};B:{“a“:“b“};C:{“Context“:0};D:不确定。 package main imp

2023-07-29,,

2022-07-20:以下go语言代码是关于json 和 context的,输出什么?A:{};B:{“a”:“b”};C:{“Context”:0};D:不确定

package main

import (
"context"
"encoding/json"
"fmt"
) func main() {
data, _ := json.Marshal(context.WithValue(context.Background(), "a", "b"))
fmt.Println(string(data))
}

答案2022-07-20:

答案选C。WithValue 底层是 valueCtx 结构体,其中 key、val 两个字段未导出,这里存放 “a” 和 “b”,同时还内嵌了 Context 接口。根据 Marshal 的规则,非导出的不会被序列化。而内嵌 Context 相当于导出了 Context 字段,而它的值是 context.Background(),即 background = new(emptyCtx),emptyCtx 实际是 int 类型,因此选 C。

2022-07-20:以下go语言代码是关于json 和 context的,输出什么?A:{};B:{“a“:“b“};C:{“Context“:0};D:不确定。 package main imp的相关教程结束。

《2022-07-20:以下go语言代码是关于json 和 context的,输出什么?A:{};B:{“a“:“b“};C:{“Context“:0};D:不确定。 package main imp.doc》

下载本文的Word格式文档,以方便收藏与打印。