在 map[string]any 的复合字面量中出现了意外的换行符。

huangapple go评论84阅读模式
英文:

Unexpected newline in composite literal for a map[string]any

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是Go语言的新手,我尝试构建一个Json构建器功能来进行练习。我的目标是创建一个递归库来构建Json。

这是我在"second"字段上遇到的警告信息:

组合文字中出现意外换行符

这是我的尝试,我在这里没有看到错误:

package main

import (
    "fmt"
)

type JsonNode struct{
    fields map[string]interface{}
}

func BuildJson (fields) JsonNode {
    jn := &JsonNode{}
    for key,value := range fields {
         jn.fields[key] = value
    }

    return jn
}

func main () {
    json := BuildJson(
        map[string]interface{}{
            "first": 1,
            "second": BuildJson(map[string]interface{}{"child": "test"}) // 此行出现错误。
        }
    )

    fmt.Printf(json)
}
英文:

I'm new to Go and I try to build a Json-builder functionality to practice. My aim is to create a recursive library to build json.

This is the warning I get for the "second" field.

Unexpected newline in composite literal 

and here's my attempt. I don't see a mistake here:

package main

import (
    "fmt"
)

type JsonNode struct{
    fields map[string]interface{}
}

func BuildJson (fields) JsonNode {
    jn := &JsonNode{}
    for key,value := range fields {
	     jn.fields[key] = value
    }

    return jn
}

func main () {
    json := BuildJson(
	    map[string]any{
		    "first": 1,
		    "second": BuildJson(map[string]any{"child": "test"}) // Error for this line.
	    }
    )

    fmt.Printf(json)
}

答案1

得分: 2

你的代码中有多个错误。这个版本是正确的,我建议你使用一些能在编译之前报告错误的集成开发环境(IDE),它们有时会自动修复错误。

package main

import (
	"fmt"
)

type JsonNode struct {
	fields map[string]interface{}
}

func BuildJson(fields map[string]interface{}) JsonNode {
	jn := &JsonNode{}
	jn.fields = make(map[string]interface{})
	for key, value := range fields {
		jn.fields[key] = value
	}

	return *jn
}

func main() {
	json := BuildJson(
		map[string]interface{}{
			"first":  1,
			"second": BuildJson(map[string]interface{}{"child": "test"}), // 此行有错误。
		},
	)

	fmt.Println(json)
}

playground

英文:

You have multiple errors in your code. This version works, I suggest you use some IDE that report errors prior to compilation (they sometimes fix it for you).

package main

import (
	"fmt"
)

type JsonNode struct {
	fields map[string]interface{}
}

func BuildJson(fields map[string]any) JsonNode {
	jn := &JsonNode{}
	jn.fields = make(map[string]interface{})
	for key, value := range fields {
		jn.fields[key] = value
	}

	return *jn
}

func main() {
	json := BuildJson(
		map[string]any{
			"first":  1,
			"second": BuildJson(map[string]any{"child": "test"}), // Error for this line.
		},
	)

	fmt.Println(json)
}

playground

huangapple
  • 本文由 发表于 2023年1月6日 08:17:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75025745.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定