Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
}

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading