Home > front end >  Unexpected newline in composite literal for a map[string]any
Unexpected newline in composite literal for a map[string]any

Time:01-06

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

CodePudding user response:

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

  •  Tags:  
  • go
  • Related